[MySQL]Automatic MySQL Backup

Create the backup.sh Script

Create a new backup.sh file with the following content:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
db_user="Your database user"
db_passwd="Your password"
db_name="Your database name"

# Backup file storage directory — you need to change this directory
backup_dir="/home/mysqlbackup"

# Date format for backup files (dd-mm-yyyy)
time="$(date +"%Y%m%d%H%M%S")"

# Execute the backup command
mysqldump -h localhost -u $db_user -p$db_passwd --all-databases --sock=/var/lib/mysql/mysql.sock > "$backup_dir/db_$time.sql"

Then, grant execution permissions and run the script:

1
2
chmod +x ./backup.sh
bash -x ./backup.sh

If you get a socket error, you need to specify sock. See: http://blog.csdn.net/seteor/article/details/18356079.

Create a Scheduled Task

Edit the crontab:

1
crontab -e

In the editor, add the following line:

1
00 23 * * * /home/mysqlbackup/backup.sh

This command will execute backup.sh every day at 23:00, backing up the database to /home/mysqlbackup.

View scheduled tasks:

1
crontab -l