Remco Haszing
Remco Haszing

Reputation: 7809

Run additional command when rsync detects a file

I am currently running the following script to make an automatic backup of my Music:

#!/bin/bash

while :; do
    rsync -ruv /mnt/hdd1/Music/ /mnt/hdd2/Music/
done

Whenever a new file is added to my music folder, it is detected by rsync and it is copied to my other disk. This script runs fine, but I would also like to convert the detected file to an ogg opus file for putting on my phone.

My question is: How do I run a command on a new file found by rsync -u?

I will also accept answers which work totally differently, but have the same result.

Upvotes: 1

Views: 469

Answers (1)

John1024
John1024

Reputation: 113834

rsync -ruv  /mnt/hdd1/Music /mnt/hdd2/ | sed -n 's|^Music/||p' >~/filelist.tmp
while IFS= read filename
do
    [ -f "$filename" ] || continue
    # do something with file
    echo "Now processing '$filename'"
done <~/filelist.tmp

With the -v option, rsync prints the names of files it copies to stdout. I use sed to capture just those filenames, excluding the informational messages, to a file. The filenames in that file can be processed later as you like.

The approach with sed above depends on rsync displaying filenames starting with the final part of the source directory, e.g. "Music/" in my example above, which is then removed assuming that you don't need it. Alternately, one could try an explicit approach for excluding noise messages.

Upvotes: 2

Related Questions