[code] A very simple backup script for my laptop

My laptop runs Linux, so I wanted to write a very simple script to backup my home area, and anything else that might be important.  There are many of these already on the web, but it was interesting and useful for me to write myself one as frankly it is not very hard.

We are using rsync to copy to the data, so that we only have to copy the changes.  It would be clever to change this to rsnapshot at a later time, as that would be better.  rsync is using authorised keys, so that it doesn’t ask me for a password.  There are many tutorials on the web how to do that.  (One day I might even write one.

The script first has to determine if my laptop is at home.  This is done by looking to see if it can see the SID of my home WiFi.  I admit this is not perfect, I am not currently checking if that _is_ the WiFi I am connected to but it should be good enough to stop the script trying to run when I am in a coffee shop or somewhere.

—-

#!/bin/bash

# Variables and other repeated things.
WIFI=”My WiFI SID”

TARGET=”user@host:/path/”   # note the trailing /
KEY=”ssh -i /root/.ssh/rsync-key”
EXCLUDE=”–exclude-from /root/exclude.txt”   # a list of directories to skip like .cache
LOGFILE=”/root/backup.out”

#Test if we are at home.
# If we can’t then we should just stop and fail.

iwlist wlan1 scan | grep ESSID | grep $WIFI > /dev/null || exit 1

# Nuke the old logfile,  This means we can also use the log file as a quick and dirty way of telling when the last backup ran.
cat /dev/null > $LOGFILE

# The magic rsync commands,  we are backing up /etc,  /root, and my home dir.  That should cover most of the places where interesting things could be stored.
rsync -avzhe “$KEY” /etc $TARGET >> $LOGFILE
rsync -avzhe “$KEY” /root $TARGET >> $LOGFILE
rsync -avzhe “$KEY” $EXCLUDE /home/russ $TARGET >> $LOGFILE

# exit successfully.

exit 0
—-
Add this to run from roots cron every half hour or so and everything will be magically backed up.

Yes there are many ways that this script can be improved, it could alert me if there are problems or if it hasn’t run in a while. But as a quick and useful script it does the job.

Leave a Reply

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