shell脚本备份mysql数据库

发布时间:2020-10-03编辑:脚本学堂
本文介绍下,用shell脚本备份mysql数据库的例子,有需要的朋友参考下吧。

在linux中,用shell 脚本对mysql数据库备份,是最常见的了。
这里分享一段脚本,供大家参考。
 

复制代码 代码示例:
#!/bin/bash
# 备份mysql数据库的shell脚本
### SETUP MYSQL LOGIN ###
MUSER='YOUR-MySQL_USERNAME'
MPASS='YOUR-MySQL_PASSWORD'
MHOST="127.0.0.1"
 
### 如果要输出详细信息,请设置为1
VERBOSE=0
 
### 命令路径设置 ###
GZIP=/bin/gzip
MYSQL=/usr/bin/mysql
MYSQLDUMP=/usr/bin/mysqldump
RM=/bin/rm
MKDIR=/bin/mkdir
MYSQLADMIN=/usr/bin/mysqladmin
GREP=/bin/grep
 
### Setup dump directory ###
BAKRSNROOT=/tmp/rsnapshot/mysql
 
#####################################
### ----[ No Editing below ]------###
#####################################
### 默认的时间格式 ###
TIME_FORMAT='%H_%M_%S%P'
 
### Make a backup ###
backup_mysql_rsnapshot(){
        local DBS="$($MYSQL -u $MUSER -h $MHOST -p$MPASS -Bse 'show databases')"
        local db="";
        [ ! -d $BAKRSNROOT ] && ${MKDIR} -p $BAKRSNROOT
        ${RM} -f $BAKRSNROOT/* >/dev/null 2>&1
 [ $VERBOSE -eq 1 ] && echo "*** Dumping MySQL Database ***"
 [ $VERBOSE -eq 1 ] && echo -n "Database> "
        for db in $DBS
        do
                local tTime=$(date +"${TIME_FORMAT}")
                local FILE="${BAKRSNROOT}/${db}.${tTime}.gz"
  [ $VERBOSE -eq 1 ] && echo -n "$db.."
                ${MYSQLDUMP} -u ${MUSER} -h ${MHOST} -p${MPASS} $db | ${GZIP} -9 > $FILE
        done
  [ $VERBOSE -eq 1 ] && echo ""
  [ $VERBOSE -eq 1 ] && echo "*** Backup done [ files wrote to $BAKRSNROOT] ***"
}
 
### Die on demand with message ###
die(){
 echo "$@"
 exit 999
}
 
### Make sure bins exists.. else die
verify_bins(){
 [ ! -x $GZIP ] && die "File $GZIP does not exists. Make sure correct path is set in $0."
 [ ! -x $MYSQL ] && die "File $MYSQL does not exists. Make sure correct path is set in $0."
 [ ! -x $MYSQLDUMP ] && die "File $MYSQLDUMP does not exists. Make sure correct path is set in $0."
 [ ! -x $RM ] && die "File $RM does not exists. Make sure correct path is set in $0."
 [ ! -x $MKDIR ] && die "File $MKDIR does not exists. Make sure correct path is set in $0."
 [ ! -x $MYSQLADMIN ] && die "File $MYSQLADMIN does not exists. Make sure correct path is set in $0."
 [ ! -x $GREP ] && die "File $GREP does not exists. Make sure correct path is set in $0."
}
 
### Make sure we can connect to server ... else die
verify_mysql_connection(){
 $MYSQLADMIN  -u $MUSER -h $MHOST -p$MPASS ping | $GREP 'alive'>/dev/null
 [ $? -eq 0 ] || die "Error: Cannot connect to MySQL Server. Make sure username and password are set correctly in $0"
}
 
### main ####
verify_bins
verify_mysql_connection
backup_mysql_rsnapshot