How to Set Up a Cron to Take MySQL Database Backup Daily and Remove the Older Backup Files that are Older than 10 Days?

1. Log in to your Linux server using SSH.

2. Open your crontab using this command – 

Crontab -e

3. Enter the cronjob given below to take your database backup daily – 

00 12 * * * mysqldump -uroot -ppassword --opt accu_4 > /home/mysql_backup/accu_4-$( date +"\%Y_\%m_\%d" ).sql >> /dev/null 2>&1

  • 00 12 – It shows that cron will back up the MySQL database at 12 hours and 00 minutes daily.
  • Change accu_4 – with the actual database name.
  • Change /home/mysql_backup/ - with your exact location of the backup.
  • /dev/null 2>&1 – This will ignore any warning or error received with your cron.

4. Verify the backup in your backup directory to check if the backup is working fine. 

Suppose you are running a daily database backup. In that case, you also need to run a script that can remove the backup after a specific period, or it will keep increasing your server disk space. 

The following steps will remove the database backup after 10 days from the backup directory –  

1. Create a file using your preferred editor in the /opt location, and add this code to it – 


find /home/mysql_backup/*.sql -mtime +10 -exec rm -rf {} \;

2. Now set this cronjob – 

00 13 * * * cd /opt/ && sh

This will remove the backup file for older than 10 days.

Was this answer helpful?

« Back