MySQL backup script and keep it for 7 days

Time:2020-11-23

Script requirements:

Backup MySQL database every day and keep the script for 7 days.

Stored in the / opt / dbbak directory.

The script name is database_ xxxx-xx- xx.sql

Script content:


#!/bin/bash
export NOW="$(date +"%Y-%m-%d")"
export DATA_DIR=/opt/dbbak
/usr/local/ywgh/mysql/bin/mysqldump --opt -uroot –p 'mypassword' ywghblog > $DATA_DIR/ywghblog/ywghblog_$NOW.sql
find $DATA_DIR/ywghblog -type f -name "*.sql" -mtime +7 -exec rm -rf {} \;

Script explanation:

First, define a variable “now” to take the current year, month and day,

In the definition of a directory variable data_ DIR,

Then use the mysqldump command to backup the library to the specified directory,

Finally, use the find command to find the SQL files in the specified directory, and delete the files beyond 7 days.

-Mtime + is to find files that are seven days away

-Mtime – is to find the files within 7 days

-Exec is to execute the following command

Please modify the script according to your own needs.

Knowledge point extension: automatic backup of MySQL database script

VI dbbackup.sh In the open editor, enter:


#!/bin/bash
/usr/local/mysql/bin/mysqldump -uuser -ppasswd databasename > /home/wwwroot/backup/date_$(date '+%Y%m%d').sql

Command means to usemysqldumpThe export name isdatabasenameTo the / home / wwwroot / backup / folder and named date_ Date. SQL, – u is followed by your MySQL user name, – P is followed by MySQL password, and databasename is the name of the database to be backed up. Replace these three with your own.

Modify the permissions and execute the backup script to see if the backup is successful


chmod +x dbbackup.sh
sh dbbackup.sh

If you have no problem with the scheduled data backup, check it automatically

crontab -e

Enter the scheduled task in the open file:

56 23 * * * /root/dbbackup.sh

Then press ESC and type: WQ to exit editing and save the file.

OK, the scheduled task is created. It is backed up at 23:56 every day dbbackup.sh Back up the database.

summary

The above is the MySQL backup script introduced to you by Xiaobian and kept for 7 days. I hope it will be helpful for you. If you have any questions, please leave me a message, and the editor will reply to you in time. Thank you very much for your support to the developeppaer website!
If you think this article is helpful to you, welcome to reprint, please indicate the source, thank you!