Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
September 30 2018 - Using rsync as a Backup Method

Using rsync as a Backup Method

I like rsync. It's an amazing little Unix utility that allows the user to sync files across two drives/folder structures. I use it personally for backuping up photos and other important documents to a mounted USB drive. I then (periodically) update the drive and keep it locked up in a safe place when it's not in use.

Here is an example script that you could use to backup your Dropbox's Code, Documents, Sites and Photos directories (on Windows, using Git Bash):

#!/bin/bash

rsync --size-only \
      --delete \
      --recursive \
      --delete-excluded \
      --verbose \
      --exclude node_modules \
      --exclude .dropbox \
      --exclude .meteor/local \
      //localhost/c$/Users/$(whoami)/Dropbox/Code \
      //localhost/c$/Users/$(whoami)/Dropbox/Documents \
      //localhost/c$/Users/$(whoami)/Dropbox/Sites \
      //localhost/c$/Users/$(whoami)/Dropbox/Photos \
      //localhost/s$/ \
      | tee //localhost/s$/backup.log

This script will also use tee to pipe the output to a backup.log file.

Using rsync for Code Deployment

We can also use rsync for code deployment. This works best with HTML/PHP style deployments where we only need to change the files on the server which have changed locally. We can setup SSH keys and configuration so that we can just call the name of the server inside our Bash script. Checkout this example rsync-local-prod.bash script which I wrote that could be used for updating a WordPress website:

rsync -rv --size-only --delete --exclude-from=.rsyncignore . servername:/home/user/public_html/

The neat thing is you can also point rsync to an excludes file (notice the --exclude-from=.rsyncignore option above).

The .rsyncignore file can could contain things like:

# rysnc specific ignores
.rsyncignore
rsync*.bash
rsync*.sh
# Exclude my `workfiles` directory off of the root of the tree
/workfiles/
# Exclude common webserver files
/cgi-bin/
# Exclude node_modules and .git folders anywhere in the tree
node_modules
.git
# Wordpress stuff
wp-config.php
cache
supercache
# Exclude WP media directory
uploads

This way you don't have to list all those ignores inside the same script. Just like a .gitignore file you can add all of the ignored files to a single file (line by line) with the --exclude-from= option. 😻

So go ahead, and give rsync a try today and break away from those FTP woes! I'm sure that you'll love it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.