Ubuntu – rsync: Sync folders, but keep extra files in target

backupcommand linedirectoryrsyncsync

I'm getting started with rsync and tried to use it to keep two folders on local system synced. I have a source folder, whose content changes over time (some files get added, some changes and some deleted) and a target folder that I want to almost be a mirror of the source. So what I tried was using rsync like this:

rsync -a --delete "${source_dir}" "${target_dir}";

This does keep the contents of target the exact same as the contents of source. However, I would like to be able to add some files to target and not to source, but I don't want them to be deleted everytime I do rsync. On the other hand, files that used to be synced and then got deleted in source should still be deleted.

Is there a way to do this without having to alter the command for every file that I want excluded?

Update: I should mention that I am not limited to rsync. If another program gets the job done, that's fine too. I just tried to solve this using rsync.

Best Answer

rsync has an option called --exclude-from option which allows you to create a file containing a list of any files which you would like to exclude. You can update this file whenever you want to add a new exclusion, or remove an old one.

If you create the exclude file at /home/user/rsync_exclude the new command would be:

rsync -a --delete --exclude-from="/home/user/rsync_exclude" "${source_dir}" "${target_dir}"

When creating the exclude list file, you should put each exclusion rule on a separate line. The exclusions are relative to your source directory. If your /home/user/rsync_exclude file contained the following options:

secret_file
first_dir/subdir/*
second_dir/common_name.*
  • Any file or directory called secret_file in your source directory will be excluded.
  • Any files in ${source_dir}/first_dir/subdir will be excluded, but an empty version of subdir will be synced.
  • Any files in ${source_dir}/second_dir with a prefix of common_name. will be ignored. So common_name.txt, common_name.jpg etc.