Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell rsync to run only if the destination directory exists?

Tags:

bash

rsync

I have this bash script running my backup to an external hard drive... only if that drive is mounted (OS X):

DIR=/Volumes/External; 
if [ -e $DIR ]; 
then rsync -av ~/dir_to_backup $DIR; 
else echo "$DIR does not exist"; 
fi

This works, but I sense I am misreading the rsync man page. Is there a builtin rsync option to abort the run if the top level destination directory does not exist? Without testing for the existence of /Volumes/External, a directory will be created by that name if it isn't already mounted.

like image 280
Marcus Avatar asked Jan 04 '09 14:01

Marcus


People also ask

Does rsync automatically skip existing files?

Rsync with --ignore-existing-files: We can also skip the already existing files on the destination. This can generally be used when we are performing backups using the –link-dest option, while continuing a backup run that got interrupted. So any files that do not exist on the destination will be copied over.

Does rsync create destination directory?

Copy/Sync a File on a Local Computer In the above example, you can see that if the destination is not already existed rsync will create a directory automatically for the destination.

Does rsync overwrite directories?

By default, the rsync program only looks to see if the files are different in size and timestamp. It doesn't care which file is newer, if it is different, it gets overwritten.

How do I rsync all files in a directory?

Copy multiple files locally If you want to copy multiple files at once from one location to another within your system, you can do so by typing rsync followed by source files name and the destination directory.


2 Answers

AFAIK no, but you can simulate the behavour with a trailing slash:

rsync -av dir_to_backup /Volumes/External/;

It will exit with an error if the directory does not exist (which may or may not be desired).

Also, you can always optimize away the if:

test -e $DIR && rsync -av ...

like image 120
mjy Avatar answered Sep 22 '22 15:09

mjy


These two flags look like what you're looking for:

--existing, --ignore-non-existing

From the man page:

--existing, --ignore-non-existing
This tells rsync to skip creating files (including directories) that do not exist yet on the destination. If this option is combined with the --ignore-existing option, no files will be updated (which can be useful if all you want to do is delete extraneous files).

like image 36
Ray Booysen Avatar answered Sep 20 '22 15:09

Ray Booysen