0

I think this is simple but I can't find anything in my googling, maybe I'm searching the wrong terms.

I have a machine that syncs itself to another machine. If there are changes to a file on the remote machine, then I need to run additional scripts on the local machine. But, I can't seem to figure out how to set a condition on an rsync command allowing it to only run additional scripts if the file has been changed/updated.

Thanks a bunch in advance!

1 Answer 1

0

There isn't an obvious answer, like an option that lets you specify a script to be run if changes were found. However, you could use the --stats flag to generate statistics about what happened, parse them, and make an educated guess.

$ rsync -avP --stats src dest 
sending incremental file list
...

Number of files: 10
Number of files transferred: 2
Total file size: 27 bytes
Total transferred file size: 27 bytes
Literal data: 27 bytes
Matched data: 0 bytes
File list size: 253
File list generation time: 0.001 seconds
File list transfer time: 0.000 seconds
Total bytes sent: 411
Total bytes received: 82

sent 411 bytes  received 82 bytes  986.00 bytes/sec
total size is 27  speedup is 0.05

You could capture that and look for the Number of files transferred: 2

$ rsync -avP --stats src dest | grep 'Number of files transferred:' 
Number of files transferred: 0
$ touch src/another
$ rsync -avP --stats src dest | grep 'Number of files transferred:'
Number of files transferred: 1

Or, to be more paranoid, capture the output and report back either a number of files or if the line wasn't found (in case the way the stats are reported ever changes).

#!/bin/bash

set -e

tmpfile=$(mktemp)

rsync -avP --stats src dest | grep 'Number of files transferred:' >"$tmpfile"

if [[ $(wc -l < "$tmpfile") == "1" ]]; then
  changedfiles=$(awk '{ print $5 }' <"$tmpfile")
else
  changedfiles="ERROR"
fi
rm -f "$tmpfile"

echo CHANGEDFILES="$changedfiles"
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.