mysql backup script and delete backup files from the previous 5 days

  • 2020-05-30 21:13:08
  • OfStack

 
USER=root # Database username  
PASSWORD=cucrzmysql # Database user password  
#DATABASE=idssr # Database name  
for DATABASE in `ls /mysql/data/mysql/ | grep idss` # Database name  
do 
#WEBMASTER=849699940@qq.com # Administrator email address to send backup failure message reminder  
BACKUP_DIR=/mysql_bak # Backup file storage path  
LOGFILE=/mysql_bak/data_backup.log # Journal file path  
DATE=`date '+%Y%m%d-%H%M'` # Date format (as file name)  
DUMPFILE=$DATABASE-$DATE.sql # Backup file name  
ARCHIVE=$DATABASE-$DATE.sql.tgz # Compressed file name  
DATE_5=`date -d "-5 day" +%Y%m%d` 

# Determines if the backup file storage directory exists, otherwise it is created  
if [ ! -d $BACKUP_DIR ];then 
mkdir -p "$BACKUP_DIR" 
fi 

# Before starting the backup, write the backup header to a journal file  
echo " ">> $LOGFILE 
echo "----------------------">> $LOGFILE 
echo "BACKUP DATE:" $(date +"%Y-%m-%d %H:%M:%S") >> $LOGFILE 
echo "----------------------">> $LOGFILE 

# Switch to the backup directory  
cd $BACKUP_DIR 
# delete 5 Days before the backup file  
rm -rf $DATABASE-$DATE_5* 
# use mysqldump  Command to backup the setup database and name the backup file after the formatted timestamp  
mysqldump --opt $DATABASE -uroot -pcucrzmysql > /$BACKUP_DIR/$DUMPFILE 
# Determine if the database backup was successful  
if [[ $? == 0 ]]; then 
# Create a zip file for the backup  
tar czvf $ARCHIVE $DUMPFILE >> $LOGFILE 2>&1 
# Enter the successful backup message into the diary file  
echo "[$ARCHIVE] Backup Successful!" >> $LOGFILE 
# Delete the original backup file, just protect it   Leave the database backup files can be compressed package  
rm -f $DUMPFILE 
else 
echo "Database Backup Fail!" >> $LOGFILE 

# Send an email reminder to the site administrator after the backup failed, as needed mailutils Or similar support for sending mail tools under the terminal  
#mail -s  " Database:$DATABASE Daily Backup Fail "  $WEBMASTER 
fi 
# Output a reminder that the backup process is over  
echo "Backup Process Done" 
done 

Related articles: