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. 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

Related Articles

How to change the MySQL timeout limit in Linux?

Please refer to the following article to change the MySQL timeout error.  Log in to your...

How To Remotely Copy Files Over SSH Without Entering Your Password?

We can easily copy the files from one Linux machine to another using SSH. Here is an example of...

How To Install PIP in Linux?

PIP called a Package management system for Python. It allows your system to install and manage...

How to Change LiteSpeed WebServer Port on cPanel?

Please refer to the following steps to change the LiteSpeed WebServer Port on cPanel. Login to...

How to change SSH port on Centos 7.x?

SSH or secure shell is a network protocol. We use it to connect and access remote servers. We can...

  • 0 Users Found This Useful

Was this answer helpful?