Mysql backing up multiple database code instances
- 2021-12-19 07:12:19
- OfStack
This article mainly introduces Mysql backup multiple database code examples, in this article through the example code introduction is very detailed, for everyone's study or work with a reference to learning value, the need for friends can refer to the following
Backup data script
#!/bin/bash
# date Yes linux Adj. 1 Commands date [ Parameter ] [+ Format ]
time=` date +%Y_%m_%d_%H_%M_%S `
# Backup output path
backupdir=/home/backup/
# Backup file path
filedir=/home/my_app/files/
# Use sql Statement to fetch all the 'test' The database at the beginning. Pass instructions through the pipeline to mysql Client; -N Indicates that the header and end of the result are not output, and the result is a pure data set
databases=(`echo 'show databases like "test%";' | mysql -N -uroot -proot`)
# Will mysqldump The output file of is passed to the gzip Compression, gzip The original file cannot be saved and the directory cannot be compressed
mysqldump -uroot -proot --databases ${databases[*]} | gzip > $backupdir/$time.sql.gz
# Back up files. zip [ Compressed output file ] [ Compressed file ]
zip -r $backupdir/$time.zip $filedir
# Delete 7 Backup files from days ago
find $backupdir -mtime +7 -name "*" -exec rm -rf {} \;
Then set crontab to run the backup script every morning
Data recovery
mysql -u root -p DATABESE_NAME < dump.sql
Or connect to the mysql client
mysql> source dump.sql