I have a secondary backup drive that is usually stored offsite, but sometimes mounted. I'd like to put something in a crontab that automatically clones my backup drive to the secondary backup if it's mounted. I know that I could do something like:

if [ -d $target_dir ]; then rsync -a --delete $src_dir $target_dir; fi

but I'm wondering if there's a way to ask rsync the same thing, without resorting to a shell script? Given that it has 6.02*10^23 command line options, you'd think so...

  • Not to make your job harder, but if you have udev available, maybe have it run the rsync when it notices the drive being attached? – Jeff Schaller Nov 2 '18 at 16:53
  • Why don't you run the command regardless? rsync will simply fail if the hard drive is not mounted. – Katu Nov 2 '18 at 17:00
  • 2
    Nice use of Avogadro's number. :) – Lewis M Nov 2 '18 at 17:01
  • @Katu, wouldn't it attempt to create a directory in the root filesystem? – Scott Deerwester Nov 2 '18 at 17:34
  • 1
    If you don't mind it erroring out you can do something like rsync /src/. /target/. The trailing /. on the path will cause it to error out if the directory doesn't exist. – Zoredache Nov 2 '18 at 18:53

Here's a trick that would probably work ... In my example, rsync will succeed if $target_dir is on the 'remote' machine (localhost), else fail (by not running the remote rsync).


src_dir=/etc;target_dir=/test/a;rsync -azp --rsync-path="[[ -d $target_dir ]] && rsync" $src_dir localhost:$target_dir

The failure result code should be 12 if the remote directory doesn't exist ... because it never actually ran the remote rsync due to the failure of "[[ -d $target_dir ]]"

12 Error in rsync protocol data stream

The caveat is you've got to use a TCP socket to get it to work, which may be slower.

Another option, via /etc/crontab (that wouldn't require a script), would be something like ..

50 23 * * * root (src_dir="/test/src_dir"; target_dir="/test/target_dir"; [ -d $src_dir ] && [ -d $target_dir ] && rsync -a -v --delete ${src_dir}/ ${target_dir}/) &>> /var/log/test.log

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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