The hosting provider I use offers a backup server. It’s very reliable, but it only supports the SFTP and RSYNC protocols. That’s all fine for regular usage, but when your backup script breaks somehow, and you need to start fresh, SFTP is not an option. Deleting millions of files across can take days.
So, what’s the solution? RSYNC to the rescue! The great file synchronization tool offers many, many options, but for this snippet I’ll keep it simple. As always, first the snippet, then the explanation.
rsync -arv --delete ~/empty_local_folder/ username@remote_server:/path/to/remote/folder/ |
Requirements
This code requires you have got a folder in your user directory called empty_local_folder
. If you don’t have this folder, you can create it by doing mkdir ~/empty_local_folder
and be sure to put nothing in it.
Configuration
In the code, you can replace the username
and remote_server
with your username and remote server name. Same goes for the /path/to/remote/folder/
, which contents of which will be deleted.
Explanation
The rsync command takes loads of arguments, but I will stick to the ones used above:
-a
The ’archive’ option. This makes sure rsync synchronizes the files, and not just copies them blindly.
-r
The ’recursive’ option. Tells rsync to travel down the directory tree and apply changes to all that lies below the /path/to/remote/folder/
.
-v
The ’verbose’ option. Gives more feedback to the user issuing the command.
--delete
The ’delete’ option. This is the most important option for this snippet. It tells rsync not only to update missing files on the remote server, but also to delete files and folders that don’t exist on the local machine. This is, essentially, what makes this snippet work.