Use crontab in Linux to automatically back up the database.
Use crontab to automatically back up databases in Linux
Here we use the crontab scheduled task addition and mysqldump to perform simple database backup. The specific steps are as follows:
1. Write a script:/serverBack/autobackmysql. sh
The content is as follows:
Method 1:
# Use mysqldump to back up database erms
/Usr/local/mysql/bin/mysqldump-uroot-ppwd erms>/serverBack/mysql_back/erms _ $ (date + "% Y _ % m _ % d "). SQL
# Find the file name starting with erms _ and ending with. SQL in/serverBack/mysql_back/, and delete the file that was modified seven days ago.
Find/serverBack/mysql_back/-mtime + 7-name "erms _ *. SQL"-exec rm-rf {}\;
Method 2:
/Usr/local/mysql/bin/mysqldump-uroot-ppwd dbname> dir/db _ 'date + % F'. SQL
# Keep the backup file for nearly one week and delete it earlier
Find/dir-mtime + 7-name "db _ *. SQL"-exec rm-rf {}\;
Method 3:
Filename = 'date + % y % m % d'
/Usr/local/mysql/bin/mysqldump-uroot-proot erms>/serverBack/mysql/$ filename. SQL
The complete shell script content is as follows:
echo "---------------------------------------------------" >> /serverBack/dbBack/dbBackLog.logecho $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup start" >> /serverBack/dbBack/dbBackLog.log/usr/local/mysql/bin/mysqldump -uroot -ppwd erms >> /serverBack/dbBack/erms_$(date +"%Y-%m-%d").sqlif [ 0 -eq $? ];thenif [ -f "/serverBack/dbBack/erms_$(date +"%Y-%m-%d").sql" ];thenecho $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup success!" >> /serverBack/dbBack/dbBackLog.logelseecho $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup fail!" >> /serverBack/dbBack/dbBackLog.logfielseecho $(date +"%Y-%m-%d %H:%M:%S") "erms Database backup error!" >> /serverBack/dbBack/dbBackLog.logfiecho "---------------------------------------------------" >> /serverBack/dbBack/dbBackLog.logfind /serverBack/mysql_back/ -mtime +7 -name "erms_*.sql" -exec rm -rf {} \;
Note: a. Here, mysqldump is preferably an absolute path. If mysqldump is used directly, it may be backed up as an empty file.
B. to ensure that the script content is correct, you can run each command separately, for example, execute the mysqldump command: /usr/local/mysql/bin/mysqldump-uroot-ppwd erms>/serverBack/mysql_back/erms _ $ (date + "% Y _ % m _ % d "). SQL
In the c. find command, the semicolon at the end cannot be omitted.
2. Add a scheduled task
Crontab-e # edit a scheduled task
Add scheduled task content:
00 15 */serverBack/autobackmysql. sh # Run the script/serverBack/autobackmysql. sh at 15:00:00 every day.
Command:
Crontab-e # edit a scheduled task
Crontab-r: delete all scheduled tasks
Crontab-l list all scheduled tasks