Bog'liq Mastering Ubuntu Server Gain expertise in the art of deploying, configuring, managing, and troubleshooting Ubuntu Server by Jay LaCroix (z-lib.org)
[ 318 ] Next, we'll add the
-b
(backup) option:
sudo rsync -avb --delete /src /target
This one is particularly useful. Normally, when a file is updated on
/src
and then
copied over to
/target
, the copy on
/target
is overwritten with the new version.
But what if you don't want any files to be replaced? The
-b
option renames files on
the target that are being overwritten, so you'll still have the original file. If you add
the
--backup-dir
option, things get really interesting:
sudo rsync -avb --delete --backup-dir=/backup/incremental /src /target
Now, we're copying files from
/src
to
/target
as we were before, but we're now
sending replaced files to the
/backup/incremental
directory. This means that when
a file is going to be replaced on the target, the original file will be copied to
/backup/
incremental
. This works because we used the
-b
option (backup) but we also used
the
--backup-dir
option, which means that the replaced files won't be renamed,
they'll simply be moved to the designated directory. This allows us to effectively
perform incremental backups.
Building on our previous example, we can use the Bash shell itself to make
incremental backups work even better. Consider these commands:
CURDATE=$(date +%m-%d-%Y)
export $CURDATE
sudo rsync -avb --delete --backup-dir=/backup/incremental/$CURDATE /src
/target
With this example, we grab the current date and store it in a variable (
CURDATE
).
We'll also
export
the new variable so that it's fully available. In the
rsync
portion
of the command, we use that variable for the
--backup-dir
option. This will copy
the replaced files to a
backup
directory named after the
date
the command was run.
Basically, if today's date was
08-17-2020
, the resulting command would be the same
as if we had run the following:
sudo rsync -avb --delete --backup-dir=/backup/incremental/08-17-2020 /
src /target
Hopefully, you can see how flexible
rsync
is and how it can be used to not only copy
files between directories and/or nodes, but also to serve as a backup solution as well
(assuming you have a remote destination to copy files to). The best part is that this
is only the beginning. If you consult the man page for
rsync
, you'll see that there are
a lot of options you can use to customize it even further. Give it some practice, and
you should get the hang of it in no time.