Home » Bash » Backup Script

The following BASH script takes exactly one argument, the directory to be backed up, and everything else is hardcoded. The script checks for a backup medium, tars and gzips the data, writes a log file, performs an extraction test and a SHA512 sum.

How it works:

1. I rotate several external hard disks which all bear the same partition label. Linux Mint automounts these to /media/niall/LABEL.

2. This invokation backs up my home directory:

niall@lucifer ~ $ ./backup.sh ~

This one backs up my memory stick for university:

niall@lucifer ~ $ ./backup.sh /media/niall/QUB2013

3. Here is the output of such a run:

Backup Job Started at Tue Nov  5 16:00:10 GMT 2013
--------------------------------------------------
SRC  : /home/niall
DST  : /media/niall/LUCIFERBACKUP/backup_Tuesday_051113_1600.tar.gz
LOG  : /var/tmp/backup_Tuesday_051113_1600.tar.gz.log
SIZE : 454M
SIZE : 913M
SIZE : 1.4G
SIZE : 1.8G
<snip>
SIZE : 33G
SIZE : 34G
SIZE : 34G
SIZE : 35G
SIZE : 35G
33452 files backed up.
Generating SHA512 hash...
Checking GZipped TAR archive integrity...
Checking SHA512 hash...
/media/niall/LUCIFERBACKUP/backup_Tuesday_051113_1600.tar.gz: OK
--------------------------------------------------
Backup Job Finished at: Tue Nov  5 17:50:05 GMT 2013

4. Source:

#!/bin/bash

function abort {
  echo "Backup failed $1 --- deleting archive $FILENAME!"
  rm "$FILEPATH/$FILENAME $FILEPATH/$FILENAME.sha512"
  echo "Done!"
  echo "Investigate the filesystem and physical device integrity of backup medium!"
  echo "Finish: $(date)"
  exit 1
}

SUFFIX=`date +%A_\%d\%m\%y_\%H\%M`
FILENAME=backup_${SUFFIX}.tar.gz
FILEPATH="/media/niall/LUCIFERBACKUP"
clear
echo "Backup Job Started at $(date)"
echo "--------------------------------------------------"
df -h | grep ${FILEPATH} > /dev/null 2>&1
if [[ $? != 0 ]]; then
  echo "Backup medium not found, exiting..."
  echo ""
  exit 1
fi
echo "SRC  : $1"
echo "DST  : $FILEPATH/$FILENAME"
echo "LOG  : /var/tmp/$FILENAME.log"
/usr/bin/time -f "\t%E real" tar -cvpzf ${FILEPATH}/${FILENAME} --one-file-system --exclude='"${SUFFIX}"' "$1" > /var/tmp/${FILENAME}.log 2>&1 &
tarPID=$!

while [ $? -eq 0 ]; do
  sleep 30
  ls -lh ${FILEPATH} | grep ${FILENAME} | awk  '{print "SIZE : " $5}'
  ps ax | grep "$tarPID" | grep -v "grep" > /dev/null 2>&1
done

FILES=$(cat /var/tmp/${FILENAME}.log | grep "$1" | wc -l)
echo "${FILES} files backed up."
echo "Generating SHA512 hash..."
sha512sum ${FILEPATH}/${FILENAME} > ${FILEPATH}/${FILENAME}.sha512
echo "Checking GZipped TAR archive integrity..."

tar -xvzf ${FILEPATH}/${FILENAME} -O > /dev/null 2>&1
if [[ $? != 0 ]]; then
  abort "extraction test to /dev/null."
fi

echo "Checking SHA512 hash..."
sha512sum -c ${FILEPATH}/${FILENAME}.sha512

if [[ $? != 0 ]]; then
  abort "SHA512 checksum comparison."
fi

echo "--------------------------------------------------"
echo "Backup Job Finished at: $(date)"
exit 0