Bash/Shell Script: Daily backup of database (with animated SPINNER graphic!)

Submitted by metaharper - 5 years ago

This is the script I use for daily, rolling backups that I set to run (using crontab) usually every half-hour or more depending on the volume of orders on a site. The file output appears in the form of Sun_Production_Backup.sql (or whatever day it is). I also can run it manually right before I install an extension or make other big changes by running "bash".I included an animated, spinner graphic that keeps me entertained when I run it manually. This script also writes to a log file so I can monitor any discrepancies and see how long my backups are taking over time - very helpful! I don't use credentials on the command line so this references a config file (.cnf) which contains the following: [mysqldump] user=mysqluser password=mysqlpassword I keep it in the same directory as backup script but you can store it wherever you like just so long as you update the filepath. Finally, when I'm ready to rock and/or roll, I run crontab -e from my command prompt and insert the following line: */30 * * * * bash /path/to/backups/ The last backup is ran at about 11:30pm which results in a one backup file for each day, 7 days a week. I recommend grabbing a weekly snapshot as well just to keep good archives. That's it!

    local pid=$1
    local delay=0.75
    local spinstr='|/-\'
    while [ "$(ps a | awk '{print $1}' | grep $pid)" ]; do
        local temp=${spinstr#?}
        printf " [%c]  " "$spinstr"
        local spinstr=$temp${spinstr%"$temp"}
        sleep $delay
        printf "\b\b\b\b\b\b"
    printf "    \b\b\b\b"

echo "Starting Production backup..."
# cd into wherever you store backups
cd /path/to/backups
# Record when the backup begins in a log file
echo "$(date +%a)_Production_Backup.sql starting $(date)" >> daily-backup.log
# Overwrite your previous backup
rm $(date +%a)_Production_Backup.sql
# Actually dump the good stuff. Notice the spinner command being executed simulatenously.
mysqldump --defaults-file=backup.cnf magento_db > $(date +%a)_Production_Backup.sql & spinner $!
# Record when the backup ends in a log file
echo "$(date +%a)_Production_Backup.sql finished $(date)" >> daily-backup.log
# Celebrate
echo "Production backup finished!"
Learn PHP
comments powered by Disqus
Proudly hosted on Digital Ocean