22

I'd like to automatically run a one way sync between two local directories using rsync. Meaning when a change is detected in a file of /dir1 or its subdirs, the following command should run:

rsync -rtuv /dir1 /dir2

How can I go about achieving this with fswatch?

Is it possible to supply arguments for rsync to only copy the actual files that were changed, as given by the fswatch events?

2

2 Answers 2

41
alias run_rsync='rsync -azP --exclude ".*/" --exclude ".*" --exclude "tmp/" ~/Documents/repos/my_repository username@host:~'
run_rsync; fswatch -o . | while read f; do run_rsync; done

Second line runs run_rsync once unconditionally and then - on each change in current directory (or specify exact path instead of .)

Rsync options:

  • -a - stands for "archive" and syncs recursively and preserves symbolic links, special and device files, modification times, group, owner, and permissions.
  • -z - compression
  • -P - combines the flags --progress and --partial. The first of these gives you a progress bar for the transfers and the second allows you to resume interrupted transfers
  • --exclude - excludes files by pattern

You will need fswatch:

brew install fswatch
6
  • 9
    Very nice ninja post. Perhaps using -or after fswatch would be better, for recursiveness.
    – Zoltán
    Commented Feb 27, 2017 at 22:12
  • 2
    Beware: fswatch scans entire tree even if you exclude things. github.com/emcrisostomo/fswatch/issues/151. That is, your node_modules if you have one will be completely scanned.
    – vaughan
    Commented Jul 19, 2018 at 15:05
  • Wouldn't this call rsync for every changed file, while it only needs to be called ones since rsync also checks what files have changed? Commented Aug 26, 2020 at 13:03
  • 1
    No, the -o option means --one-per-batch. See here: github.com/emcrisostomo/fswatch/wiki/….
    – Brian
    Commented Nov 18, 2021 at 3:25
  • @vaughan Oops that is huge. Is there any workarounds?
    – ch271828n
    Commented Mar 3, 2022 at 8:57
2

For a one-line solution:

function run_rsync() { rsync your_args } ; run_rsync; fswatch -o your_directory | while read f; do run_rsync; done

Thanks @Daniel for the inspiring answer.

Your Answer

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

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