The case of using shell script to maintain database regularly under Linux

Time:2020-9-14

During the epidemic period, I couldn’t be anywhere. I got sick when I was staying at home every day. After learning Linux basic command and shell programming for a week with the video of Mr. Han Shunping, I made a case of shell script to maintain the database regularly for later review and application.

The script requirements are as follows:

我把我的数据库名字换成了myDB

#Scheduled database backup
#Backup path
BACKUP=/data/backup/db
#Gets the current time as the file name
DATETIME=$(date +%Y_%m_%d_%H%M%S)

Echo "= start backup ="
Echo 'the backup path is backup / backup / backup/ DATETIME.tar.gz '

#Host computer
HOST=localhost
#User name
DB_USER=root
DB_PWD=root
DATABASE=myDB
#Create backup path
[ ! -d “BACKUP/BACKUP/BACKUP/DATETIME” ] && mkdir -p “BACKUP/BACKUP/BACKUP/DATETIME”
#Execute MySQL backup database instructions
mysqldump -uDBUSER−p{DB_USER} -pDBU​SER−p{DB_PWD} --host=$HOST $DATABASE | gzip > BACKUP/BACKUP/BACKUP/DATETIME/$DATETIME.sql.gz
#Package backup files
cd $BACKUP
tar -zcvf $DATETIME.tar.gz $DATETIME
#Delete temporary directory
rm -rf BACKUP/BACKUP/BACKUP/DATETIME

#Delete backup files 10 days ago
find $BACKUP -mtime +10 -name “*.tar.gz” -exec rm -rf {} ;
Echo "backup successful"

源码如上图

last

Adding timed tasks with crontab – e instruction
10 2 * * * /usr/sbin/mysql_db_backup.sh

Finally, the shell script is completed!

summary

This article on linux using shell scripts to maintain the database on a regular basis to introduce this, more shell scripts regularly maintain database content, please search the previous articles of developeppaer or continue to browse the relevant articles below, I hope you can support developeppaer more in the future!