There are many solutions out there for doing constant backups on a linux system (rsync being a famous one). What I wanted to do however, was write a script myself that occasionally does backups of my Documents folder for me. I decided to write it using bash and here is how it goes.
First of all, since I dont want to have to constantly invoke the script with
bash backup.sh, I tell the shell which interpreter to use. I also define some variables that will be useful later on. The DATE variable will store the date in a year-month-day format. Then we check to make sure the day is correct (we dont need backups every day or else we will run out of space) and that the storage drive is mounted. With that we create the directory that will store out backup, change to it and then begin creating a zipped tarball of the Documents directory. While all this is done, any errors encountered are logged into a file that can be read at a later time to determine what went wrong.
#!/bin/bash ROOTBAK="/home/gum/Files" BACKUPDIR="Backups" TARGET="Documents" DATE=$(date -I) #Check if it is a Saturday if [ $(date +%u) -ne 7 ] then #Check to see if the drive is mounted if [ -d $ROOTBAK/$BACKUPDIR ]; then mkdir $ROOTBAK/$BACKUPDIR/$TARGET/$DATE 2>> backup.error.log cd $ROOTBAK/$BACKUP/$TARGET/$DATE 2>> backup.error.log tar cvzf $ROOTBAK/$BACKUPDIR/$TARGET/$DATE/Documents.tar.gz /home/gum/Files/Documents else echo "The directory $ROOTBAK/$BACKUPDIR does not exist!" >> backup.error.log fi fi
This script is simple and effective, but it does not run on its own so we need to make use of a very neat utility in linux called cron (I cant seem to embedd links so please see the man page here http://www.linuxmanpages.com/man8/cron.8.php). To begin creating a cron job, you need to open up the cronjobs for the user with the command
crontab -e. This will allow you to set jobs for the current user. If you have never used the cronjobs before, the file will be empty so you might find it useful to add some comments at the top as a reminder of what each field means. So with all that, this is how I set it up on my system, but feel free to make changes as needed.
# Minute Hour Day of Month Month Day of Week Command # (0-59) (0-23) (1-31) (1-12 or Jan-Dec) (0-6 or Sun-Sat) 0 15 * * Sat /home/gum/Documents/Programming/Bash/backup/backup.sh