Easy backup bash script

Published on
Aug 8, 2011

Here I'm showing you a simple script which dumps and stores any number of databases, then compresses them into tar.gz files.

The archived files will have unique names containing script's execution time. It should run an any Linux/Unix machine. This was written as a daily backup, it doesn't delete any previous backups, nor does it implement any incremental backup functionality. It just a simple script for your joy, so have fun.

!/bin/bash # # DB Backup script by webdesignpatterns.org # # modify the following to suit your environment export BKP_DIR="/path/to/your/backupsdir" # << Modify this - the directory of your backups. export DB_USER="root" # DB username export DB_PASSWD="*****password*****" # DB password databases=( "database_name_1" "database_name_2" "database_name_3" ) # an array - don't be shy to add more DBs here # Create archive filename. day=$(date +%m.%d.%Y) for i in "${databases[@]}" do archive_file="$i-$day.sql.tar.gz" echo "* Creating new backup..." mysqldump $i -u root -p$DB_PASSWD > $BKP_DIR/$i-$day.sql echo "* Archiving..." tar czf $BKP_DIR/$i-$day.sql.tar.gz $BKP_DIR/$i-$day.sql echo "* Removing raw files" rm $BKP_DIR/$i-$day.sql done echo "Done" exit 0

How to run it.

You'll have to copy the code and paste it into some file, say daily_backup.sh. Then put it into some directory, preferably into something like /etc/cron.daily/ which exists by default in Ubuntu for example. Please note: scripts in Ubuntu system in the /etc/cron.daily/ need to be without extensions. You can actually test which scrips will run by executing:

run-parts /etc/cron.daily --test


mv /etc/cron.daily/daily_backup.sh /etc/cron.daily/daily_backup

Now you'll have to say when to execute it, so:

sudo crontab -e


# m h dom mon dow command 40 07 * * * root run-parts /etc/cron.daily

Also give the relvant execution permissions to the script:

chmod uga+x /path/to/your/backupsdir/daily_backup.sh # /etc/cron.daily ?

This will execute everything in /etc/cron.daily each day at 7:40am. Next, naturally, you should restart your cron service like that:

sudo service cron restart

That's it.