How to set up a cron to take MySQL Database Backup daily and remove the older backup files that are older than 10 days? Print

  • 0

  1. Login to your Linux server using ssh.

  2. Open your crontab using the below command

    Crontab -e
  3. Enter the below cronjob 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 is showing that cron will backup mysql database on 12 hours and 00 minutes everyday.

  • Change accu_4 -- with the actual database name.

  • Change /home/mysql_backup/ -- with your exact location of backup.

  •  /dev/null 2>&1 -- This will ignore any warning or error that is receiving with your cron.

  1. Verify the backup at your backup directory to check the backup is working fine. 

If you are running a daily database backup, 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. Following steps will remove the database backup after 10 days from the backup directory. 

  1. Create a file using your favorite editor at the location /opt and add the below code in it. 

    vi remove.sh
    find /home/mysql_backup/*.sql -mtime +10 -exec rm -rf {} \;
  1. Now set the below cronjob. This will remove the backup file for older than 10 days.

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

Was this answer helpful?

« Back
Sign up for a newsletter

chat