Raspberry Pi – Backup script

So I’ve made a little script for the Raspberry Pi to backup this device on the fly.

Note: It probably isn’t the best way to backup a device once it is running but sometimes it might be the only backup left. As the Pi is notorious for damaging SD cards: http://raspberrypi.stackexchange.com/questions/7040/is-my-raspberry-pi-permanently-damaging-sd-cards

Here’s the script:

if [ "$#" -ne 5 ]; then
        me=`basename $0`
        echo "Usage: $me     "
        exit
fi
 
if [ ! -d "/mnt" ]; then
        echo "No /mnt folder found"
        exit
fi
 
if [ ! -d "/mnt/network/backup" ]; then
        echo "No /mnt/network/backup folder, creating one..."
        mkdir -p /mnt/network/backup 2> /dev/null
fi
 
if [ ! -d "/mnt/network/backup" ]; then
        echo "Couldn't create folder. Are you root?"
        exit
fi
 
shares=$(df -h | grep -i $2)
 
if [ "$shares" != "" ]; then
        echo "Share already mounted."
        echo "Unmounting samba shares..."
        timeout=0
 
        while [ "$shares" != "" ]
        do
                umount -a -t cifs -l
 
                shares=$(df -h | grep -i $2)
                sleep 1
                timeout=`expr $timeout + 1`
 
                if [ "$timeout" -gt 60 ]; then
                        echo "ERROR: Unmount time-out"
                        exit
                fi
        done
fi
 
echo "Mounting $3@$2..."
 
mount -t cifs -o user=$3,password=$4 $2 /mnt/network/backup
 
echo "Searching key file '$5'..."
timeout=0
while [ $timeout -lt 60 ]; do
        FILE="/mnt/network/backup/"$5
 
        timeout=`expr $timeout + 1`
        if [ -f $FILE ]; then
                timeout=100
        fi
 
        if [ $timeout -eq 60 ]; then
                echo "ERROR: Timeout in finding key file: $FILE"
                exit
        fi
        sleep 1
done
 
echo "Backup directory authorized."
 
backup=`cat /etc/hostname`-`date +%s`.dd
 
echo "Creating backup '$backup'..."
 
dd if=$1 of=/mnt/network/backup/$backup bs=4096 conv=notrunc,noerror
 
echo "Unmounting network drives..."
 
umount -a -t cifs -l
 
echo "Done!"

Usage example:

sudo /home/pi/backup.sh /dev/mmcblk0 //ip_remote_server/varia/backup username password backup.key

This script can be scheduled as a cron job every night or week with ‘crontab -e’.

Leave a Reply