Linux – rsync won’t delete files on destination

linuxrsync

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?

Best Answer

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.