Shell Script To Backup MySQL Database

Shell Script To Backup MySQL Database

Taking regular backup is as important as writing good code, and it is always recommended to take database backup every day or week depending on the size of the database and the site users count. As a developer sometimes we forget to take database backup, so the best thing is to automate this and let your server deal with this whole you can concentrate on other important things.
So first of all we have to create a Shell (.sh)script which will hold the logic to grab the data and store it in a compressed filed.

Shell Script: database_backup.sh

Now that we have created the shell script now upload it in to your fileserver where all your website files reside. If you have the database host name other then local host then you have to replace mysqldump --opt --user=${USER} --password=${PASS} ${DATABASE} > ${FILE} with this mysqldump --opt --user=${USER} --password=${PASS} --host=${DBSERVER} ${DATABASE} > ${FILE} and finally you have to add a cron to your crontab, which will run the above script on desired time.

So let say we want to take a database backup after every 6 hour, so you need to use below command to edit cron.

crontab -e

and over there write below code.

0 */6 * * * sh  /path/to/your/backup_dir/database_backup.sh

Every day in the backup_dir directory a new file will be generated namely my_db_file.sql.(date).

Share this Post:

About Raunak Gupta

I'm an expert Laravel, WooCommerce, WordPress theme and plugin developer, over the time I have developed several sites and applications. I like to help the upcoming developer, So I share my experience through this blog.  

Related Posts:

Leave a Comment

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


*