Wednesday, February 8, 2012

Linux Backup Shell Script for Files and MySQL

I assembled this script to backup my web server onto a USB thumbdrive. It mounts the thumbdrive (/dev/sdc1), backs up a couple of directories, does a MySQL dump, and then unmounts the drive. It appends the day of the week to the file name so you can run it daily as a cron job and you’ll get 7-days’ worth of backups on a rotating basis.

#!/bin/sh
####################################
#
# Backup to usb thumbdrive
#
####################################

# What to backup.
backup_files="/home/shared /etc"

# Where to backup to.
dest="/home/administrator/backup/usb"

# Create archive filename.
day=$(date +%A)
hostname=$(hostname -s)
archive_file="$hostname-$day.tgz"
sql_file="$hostname-$day.sql"

# Mount the usb thumbdrive
mount -t vfat /dev/sdc1 /home/administrator/backup/usb -o uid=1000,gid=1000,utf8,dmask=027,fmask=137
echo "Thumbdrive mounted"

# Backup MySQL
echo "Backing up MySQL to $dest/$sql_file"
date
mysqldump --all-databases --password='XXXXXXX' > $dest/$sql_file

# Print start status message.
echo "Backing up $backup_files to $dest/$archive_file"
date

# Backup the files using tar.
tar czf $dest/$archive_file $backup_files

# Print end status message.
echo "Backup finished"
date

# Long listing of files in $dest to check file sizes.
ls -lh $dest

# Unmount the usb thumbdrive
umount /home/administrator/backup/usb
echo "Thumbdrive unmounted"