Database backup script

bash icon

Hi people. This time it’s about a simple script that I have created few days back to generate automated backups of this blog site. If you host website with any of the low end boxes (cheap VPS hosting), then creating a regular backups of your data is a very good idea and in my view, a needed thing. Let’s talk less and dive in. You can use the script below to automate the database backup of your website/blog etc.


First step that you would want to do is to change the three variables on the top (DIR, EMAIL and DOMAIN). Before changing ‘DIR’, make sure that the path you will mention actually exists and is valid along with the valid email address. Secondly, you would need a working SMTP server to send the email out. I would recommend to use a different email than your domain’s email address to keep the backups in a safe location. Well, that would be it, no more edits needed in the script.

Save the content of the script in a file as: and make sure it is executable (chmod +x

# Author: Aman Hanjrah
# Email:
# Website:
# License: GPL
# Additional notes: This is a simple script to take the db backup, 'tar' it and send it as an attachment in email.
# Use at your own risk. As always, before impleming in live environment, test it thoroghly in a test env.
# Full tutorial at:
#Edit the below two parameters according to your environment and the email as your email address, the system will send the db backup to this email address.
mysqldump -u DB_USER -p`cat /home/user/.scripts/.mysql` DB_NAME > $DIR/$DOMAIN-$(date +%d.%m.%y).sql 2> $DIR/dump.log
if [ `echo $?` = 0 ]
 tar -cvjf $DIR/$DOMAIN-$(date +%d.%m.%y).sql.tar.bz2 $DIR/$DOMAIN-$(date +%d.%m.%y).sql --remove-files 2> $DIR/tar.log
 sleep 2
 echo -e "Backup of $DOMAIN on: $(date +%d.%m.%y)" | mutt -a "$DIR/$DOMAIN-$(date +%d.%m.%y).sql.tar.bz2" -s "$DOMAIN bakup, $(date +%d.%m.%y)" -- "$EMAIL"
echo -e "OH BOY! Something went wrong, db dump failed for $DOMAIN, Error Summary:n `cat $DIR/dump.log`" | mutt -s "Database dump FAILED" -- "$EMAIL"
sleep 2
find $DIR/$DOMAIN* -mtime +5 -exec rm {} ; 2> $DIR/del.log

NOTE: “/home/user/.scripts/.mysql” contains the password for my database that I am going to take the backup for. Also, do not forget to use ” ` ” before and after the location of ‘.mysql‘ file otherwise the backup will fail. The purpose of using that file instead of the actual password is, well, to not reveal the password in the script.

The last line (‘find’ command) will find all the db backups that were previously made and which are 5 days older. After searching, it will delete them automatically so as to save disk space.

Next, you would need to set a cron so that this script runs at 0000 hours everyday.

00 00 * * * /bin/sh /home/user/.scripts/

Feel free to make the changes in the script and play around. After all this is a free world 🙂

Any questions are welcome. Have fun!

Leave a Reply

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