34

I am trying to mirror a directory that changes over time to another directory. My problem is that rsync is not deleting files on destination if they aren't existing in source directory anymore. Here is a demo script:

#!/bin/sh

set -x

DIR1=/tmp/1
DIR2=/tmp/2

rm -rf $DIR1
rm -rf $DIR2

mkdir $DIR1
mkdir $DIR2

echo "foo" > $DIR1/a
echo "bar" > $DIR1/b

rsync -a $DIR1/* $DIR2

rm -f $DIR1/a

rsync -a --delete $DIR1/* $DIR2

ls -1 $DIR2

Here is the output:

+ DIR1=/tmp/1
+ DIR2=/tmp/2
+ rm -rf /tmp/1
+ rm -rf /tmp/2
+ mkdir /tmp/1
+ mkdir /tmp/2
+ echo foo
+ echo bar
+ rsync -a /tmp/1/a /tmp/1/b /tmp/2
+ rm -f /tmp/1/a
+ rsync -a --delete /tmp/1/b /tmp/2
+ ls -1 /tmp/2
a
b

As you can see, file "a" is still present in destination directory after rsync runs for the second time, which is not what I need. Am I misusing the '--delete' option?

1
  • 1
    Watch out for /* at the end of source directories. That will cause rsync to only consider those files rather than the directory itself (and the absence of files that no longer exist). Jan 17, 2013 at 18:46

3 Answers 3

13

The reason is because you are calling rsync on /tmp/1/b, which will not consider the /tmp/1/a file at all.

Your intention seems to be to rsync the directory /tmp/1/ -- if you use "/tmp/1/" as the source rather than the individual files, it will notice that "a" has been deleted from the directory and remove it from the target.

40

Remove the *. As mentioned in the rsync man pages the --delete option doesn't work with wildcard entries.

Use this instead:

rsync -a --delete $DIR1/ $DIR2/

" --delete This tells rsync to delete extraneous files from the receiving side (ones that aren’t on the sending side), but only for the directories that are being synchronized. You must have asked rsync to send the whole directory (e.g. dir or dir/) without using a wildcard for the directory’s contents (e.g. dir/*) since the wildcard is expanded by the shell and rsync thus gets a request to transfer individual files, not the files' parent directory. Files that are excluded from the transfer are also excluded from being deleted unless you use the --delete-excluded option or mark the rules as only matching on the sending side (see the include/exclude modifiers in the FILTER RULES section). "

1
  • 1
    This is functionally the same as Sven's answer from 2011. Feb 21, 2017 at 22:16
14

If you change the second rsync line to rsync -a --delete $DIR1/ $DIR2 (without the *) it will work. The reason is that the shell expands the * to the file names in the first directory, which is only b in your case, so the missing file a won't be considered at all by rsync, as the command that gets executed is actually rsync -a --delete $DIR1/b $DIR2.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .