Rsync copy and source deletion

How can I move files with rsync? I need to copy files and after a successful transfer, delete source files. How can I do that?
Sometimes a backup needs to move files, not only copy them. This is usually needed on “Archive” backups type.
That means that sometimes we want to delete some files but we need to keep copies by any reason (legal, for instance).
Or you just want to move files from one location to another.
Of course, in any case, files in destination folder will not be deleted.
In this post, we explain how to do this by using “rsync”.
If you need to create a regular backup, check our post Backup with rsync.

Objective

We want to use rsync to copy files and, after a successful copy, we want those source files to be deleted.
The copied files in the destination folder will not be deleted at any moment by rsync.
Long story short, we want to move or archive files using rsync.

Local example

In this case we have a path we want to archive in a backup folder, both are mounted in the same server.
They can be local devices or network devices (smbfs/cifs, nfs, sshfs, …), it won’t change the way we use “rsync”.
In this example we need to archive the files in “/opt/service/reports” and store them in “/mnt/backupUnit/legacyreports”.
Once the files are transferred, they are deleted from “/opt/service/reports”.

rsync -rtvlpgou \
--stats \
--remove-source-files \
--log-file=/mnt/backupUnit/reportbackup.log \
/opt/service/reports \
/mnt/backupUnit/legacyreports

Modify the example to adapt it to your needs. Don’t forget at least the source path, the destination directory and log path and name.
You can check “Rsync options” to find out the meaning of every modification that has been used.

Other examples

If you need to move/archive files but from a remote server, check our examples in  Backup with rsync and combine them to get the solution to your problem.
If you have any question, you can use comment section below.

Rsync options

Let’s see some of the key flags to use rsync as a moving/archiving tool.
Check Backup with rsync to find out the meaning of the rest of the flags.

-u

This flag, forces rsync to ignore newer files that already exist in the destination directory.
If the modification date is equal, it will be updated if the sizes are different.

–remove-source-files

This flag removes all files that have been successfully transferred from the source directory.

For more information, you can check the manual page of rsync:

man rsync

Or check the output of:

rsync --help

 

Leave a Reply

Your email address will not be published. Required fields are marked *