文章给大家介绍在linux unix中利用shell命令实现mysql 数据库自动备份脚本代码,有需要了解的朋友只需简单修改一下即可使用了.
文件名 mysql_data_backup.sh (需要执行权限)
mysql 数据库表自动备份shell 脚本 (第二版)
调用示例,代码如下:mysql_data_backup.sh
包含功能:
1.生成备份日志
2.自动检测指定数据库中的库列表,单独备份每个库,最后打包为tar文件
3.可指定备份存档文件(.tar) 保留的数目, 按时间正序清理以前的存档
4.恢复时可以登录 mysql 以后直接用 source xxx.sql 自动删除和创建数据库,并还原数据.
需要修改的变量,代码如下:
- db_host//数据库主机
- db_user//数据库帐号
- db_passwd//数据库密码
- backupFileNum//保留的备份存档文件数目,超出该数目自动清理
- backupDir//备份文件存放的目录
- logfile//日志文件路径
如何恢复数据:
参见 mysql 数据库表自动备份shell 脚本,第一版,代码如下:
- #!/bin/bash
- #mysqlinkuserconfig
- db_host=192.168.0.222
- db_user=admin
- db_passwd=123456
- #backupFilenumber
- backupFileNum=4
- #logfile
- logfile='/sqlbackup/backup.log'
- #backupofdirectoryDonotbring/
- backupDir="/sqlbackup"
- #checkdatabasename
- echo'Backupbegin'
- begin_time=`date'+%s'`
- #getdatabaseslist
- databases_content=`mysqlshow-u$db_user-p$db_passwd-h$db_host|sed's/|//g'|sed's///g'|sed'1,4d'|sed'$d'`
- #checkdatabasesifemptyedthenexit
- databases_content_check=`echo-n$databases_content>/tmp/mysql_backup_check.tmp`
- if[!-s/tmp/mysql_backup_check.tmp];then
- echo'DatabaseEmptyedBackupstop.'
- exit
- fi
- #planbackupofsqldatabases
- databases=(${databases_content})
- #getdatabaseslength
- databases_len=${#databases[*]}
- #backupofdirectoryfordate
- datestamp=$(date"+%Y%m%d")
- #finalbackupdirectroy
- fileDir="$backupDir/$datestamp"
- #autocreatetargetdirectory
- if[!-d$backupDir];then
- mkdir$backupDir
- fi
- if[!-d$fileDir];then
- mkdir$fileDir
- fi
- if[!-d$logfile];then
- touch$logfile
- fi
- echo"total$databases_lendatabases."
- for((i=0;i<$databases_len;i++))
- do
- dbName="${databases[$i]}"
- fileName="${databases[$i]}.sql"
- filePath="$fileDir/$fileName"
- echo"Database[$dbName]Backup..."
- echo"DROPDATABASEIFEXISTS`$dbName`;">$filePath
- echo"CREATEDATABASE`$dbName`CHARACTERSET`utf8`;">>$filePath
- echo"use$dbName;">>$filePath
- mysqldump-h$db_host-u$db_user-p$db_passwd$dbName>>$filePath
- done
- #tarfiles
- cd$backupDir
- tarcvf${datestamp}.tar./${datestamp}
- #deletesourcearchive
- rm-rf./${datestamp}
- end_time=`date'+%s'`
- total_time=$[end_time-begin_time]
- echo'BackupDone'
- echo"Totaltime:${total_time}second"
- now_date=`date'+%Y-%m-%d%k:%M:%S'`
- #savelog
- echo"${now_date}:BackupDatabases:Totaltime[${total_time}s]">>$logfile
- #begincleanexcessofbackupfile
- #countbackupdirnameoflength;
- backupDir_length=`exprlength"$backupDir"`
- #gettarfilelist
- backupFile_list=`find$backupDir-name"*.tar"|sort-n-r-k1.$backupDir_length`
- #setarray
- backupFiles=(${backupFile_list})
- backupFile_length=${#backupFiles[*]}
- if[$backupFile_length-gt$backupFileNum];then
- for((i=$backupFile_length;i>$backupFileNum;i--))
- do
- fileName="${backupFiles[$i-1]}"
- rm-rf$fileName
- #savelog
- echo"file:$fileNamedeleted"
- echo"file:$fileNamedeleted">>$logfile
- done--phpfensi.com
- else
- echo"backupfilenumbernormal."
- fi