Posted on • Updated on

How To Automate Database Backup In CentOS



Step 1 - Create folders for custom scripts and database backups. 


$ mkdir custom_scripts
$ mkdir db_backups

Step 2 - Create .sh file

$ nano ~/custom_scripts/

Add the following content to the file:

mysqldump -u root -p{password123} my_site_db > ~/db-backups/my_site_db_`date +"%Y-%m-%d"`.sql

Note: set password without {…}

Add the following line to delete backups that are more than 10 days old.    

find ~/db-backups -mtime +10 -type f -delete

//full script    

mysqldump -u root -p{password123} my_site_db > ~/db-backups/my_site_db_`date +"%Y-%m-%d"`.sql
find ~/db-backups -mtime +10 -type f -delete

Step 3 - Set crontab   

$ crontab -e

Add the following line: 

* * * * * ~/custom_scripts/

Note: using * * * * * script will run every minute

To backup your database on daily basis Use 0 0  * * * 


 ⚙ Troubleshooting

To check logs :    

$ sudo cat /var/log/cron
$ sudo tail /var/log/cron

If the logs show any permissions-related errors. Make sure the script ( is executable by checking folder and file permissions.     

$ sudo chown -R $USER ~/custom_scripts   
$ sudo chmod -R 755 ~/custom_scripts


Some applications rely on a database to function. and possibly a database loss is required to terminate the application. We can restart our application with backup data if we have a database backup, and automatic database backup simplifies things even more. 

end of article

Related Posts

Join Our Newsletter

Want the latest & greatest from our blog straight to your inbox with some exclusive offers from our partners and sponsors?

We won't spam. Promise.