Bash Script for Backups

I use this script to backup the data on a Linux server each night via a cron job. What it does:

  1. Mounts a FAT32-formatted USB drive at /dev/sdb1 as /mnt/flash
  2. rsyncs the contents of /var/data to the USB drive, ignoring .tmp and Thumbs.db files, and deleting files on the destination that are not on the source
  3. Unmounts the USB drive
  4. Emails you with success or failure information

The script creates three log files:

  1. drive_usage.log
    Appends a new line after each run with the USB drive usage in bytes, without a header. Useful for tracking over time.
  2. YYYY-MM-DD.log
    Stdout from commands
  3. YYYY-MM-DD.err
    Stderr from commands

The crontab entry is
0 23 * * 1-5 /path/to/script.sh >> /path/to/cron.log 2>&1

#!/bin/bash
# Script to backup files to USB drive
# Written by Dylan Barlett
# Last modified 10/28/10

# Email recipient
RECIPIENT="name@example.com"

# Boilerplate email text
BOILERPLATE="The backup of files for `date +%A, %B %d, %G` is
complete. Flash drive usage information is displayed below. Do not
reply to this email."

# Log file for flash drive usage
USAGE_LOG="drive_usage.log"

# Date in YYYY-MM-DD format
TODAY=`date +%Y-%m-%0e`

# Log file name
LOGFILE="$TODAY.log"

# Error file name
ERRORFILE="$TODAY.err"

echo -n "Starting backup at " | tee -a $LOGFILE $ERRORFILE
date | tee -a $LOGFILE $ERRORFILE

mount -t vfat -o shortname=mixed /dev/sdb1 /mnt/flash 1>>$LOGFILE 
2>>$ERRORFILE

if [ $? -ne 0 ]; then
STATUS=$?
echo "Mount failed, aborting" | tee -a $LOGFILE $ERRORFILE
SUBJECT="Backup failed"
EMAIL_TEXT="Unable to start backup, USB drive not
inserted?"
else
time rsync --verbose --progress --partial --recursive --delete 
--modify-window=1 --times --exclude 'Thumbs.db' --exclude '*.tmp' 
/var/data/ /mnt/flash/ 1>>$LOGFILE 2>>$ERRORFILE
#| tee -a $LOGFILE $ERRORFILE

#Log the current date & time
echo -en `date` 't' >> $USAGE_LOG
#Log the USB drive usage in bytes without a header
df /mnt/flash | sed -e 1d|head -3 >> $USAGE_LOG
#Append human-readable USB drive usage with header to email text
EMAIL_TEXT="$BOILERPLATE `df -h /mnt/flash`"
echo "$EMAIL_TEXT" >> $LOGFILE
SUBJECT="Backup successful"
umount /dev/sdb1 1>>$LOGFILE 2>>$ERRORFILE
STATUS=$?
fi

echo "$EMAIL_TEXT" | mail -s "$SUBJECT" "$RECIPIENT" 1>>$LOGFILE 
2>>$ERRORFILE

echo "Exiting with status $STATUS"
exit $STATUS
Categorized: Software

Leave a Reply

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