Thursday, December 1, 2011

Using Rsync to Backup Windows

I don't normally write about Windows and I don't think I would consider today's post to be any different. That said, I am going to post about something related to Windows. I recently made the switch from Red Hat Enterprise Linux 6.1 back to Windows 7 for day to day work on my office workstation. The reason behind this was mainly just software compatibility. I found most of my work was being done on my secondary Windows workstation anyway and decided that the few advantages Linux had over Windows, for my purposes in a 70% Windows corporate environment, were just not worth the hassle of maintaining two workstations. As of yesterday I'm now running off of my HP Elitebook with Windows 7 Enterprise edition. With this switch has come several challenges, not the least of which was how to make sure I had regular, local, backups of my data.

My laptop has a 120GB SSD in it and, while they are getting better, I still don't trust the reliability of MLC SSDs. In the past, under Linux, I had just been running rsync as a cron job ever few hours while I was in the office. This had been working very well for me for some time and I wanted to find a way to accomplish the same thing under Windows. Enter a project named Cygwin. Cygwin allows you to run Linux applications inside of your Windows environment; setup is easy and you can easily expand the selection of available tools by re-running the installer. I opted to give this a try by installing a few simple utilties, bash, openssh, openssl, git and rsync.

Since this provides you a full bash shell you are able to create bash scripts just like you would in a real Linux environment so I set off creating myself a quick backup.sh script that would use rsync to back up C:\Users\my_username. I've posted the results of my work below, feel free to copy this and use it on your own windows system for backups. Feel free to post any comments or questions in the comments section below as well.

Note: Don't forget to change the variables I've noted in the comments in the script.


#!/bin/bash
#
# Will backup /cygdrive/c/Users/$username to /cygdrive/$drv/$hostname/Users/$username
#
## Change these values to match your computer
#
hostname="MY_COMPUTER" #Name of your computer
drv="g" #Drive to back up to
username="YOUR_USER" #Your username
## You might need to change "c" on the next line if your users folder is elsewhere
bkpfrm="/cygdrive/c/Users/$username"

## Nothing below here should need to be changed

# Check that drive letter entered is present, else prompt
while [ ! -d /cygdrive/$drv/ ]; do
read -p "$drv:\ does not appear to be a valid drive letter, please enter the correct drive letter: " drv1
if [ ! -z $drv1 ]; then #Change drive to new value if one is entered
drv="$drv1"
fi
done
rsync -au --delete $bkpfrm /cygdrive/$drv/$hostname/Users/$username