阿里狼 发表于 2018-9-18 09:03:43

结合Git实现Mysql差异备份,可用于生产环境

#!/bin/bash  
#created by lihuibin
  
#date 2013-8-30
  
#descexec mysqldump mysqlsql file from mysqlserver to git
  
time=`date '+%F %R'`
  
mysql_user="backup_user"
  
mysql_password="backup_passwd"
  
mysql_host="127.0.0.1"
  
mysql_port="3306"
  
tar_path=/root/shell/mysql_backup
  
backup_db_arr=("testdb1" "testdb2")#需要备份的数据库列表
  
#backup_db_arr=()
  
exclude_db_arr=("exdb1" "exdb2")   #排除备份的数据库列表当backup_db_arr为空的时候,exclude_db_arr生效,不为空时仅backup_db_arr有效
  
[ -d $tar_path ]
  
is_first_backup=$?
  
in_array() {
  local hay needle=$1
  shift
  for hay; do
  [[ $hay == $needle ]] && return 0
  done
  return 1
  
}
  
backup_length=${#backup_db_arr[@]}
  
#echo $backup_length
  
exclude_length=${#exclude_db_arr[@]}
  
#echo $exclude_length;
  
#in_array "dopool_blog" ${backup_db_arr[@]} && echo hit || echo miss
  
for dbname in `mysql -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password -e "show databases" |sed '1,2d'`
  
do
  if [ $backup_length -gt 0 ]; then
  in_array $dbname ${backup_db_arr[@]} || continue
  elif [ $backup_length -eq 0 -a $exclude_length -gt 0 ]; then
  in_array $dbname ${exclude_db_arr[@]} && continue
  fi
  for tablename in `mysql -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password -e "show tables from $dbname" |sed '1d'`
  do
  mkdir -p $tar_path/$dbname/
  /usr/bin/mysqldump --lock-tables=TRUE--extended-insert=FALSE --complete-insert=TRUE -h$mysql_host -P$mysql_port -u$mysql_user -p$mysql_password $dbname $tablename > $tar_path/$dbname/$tablename.sql
  done
  
done
  
init_git(){
  
tar_path=`dirname $1`
  
dir_name=`basename $1`
  
cd $1
  
git init
  
git add .
  
git commit -a -m "init $time"
  
cd $tar_path
  
git clone --bare $dir_name/
  
rm -rf $dir_name
  
git clone $dir_name.git
  
}
  
[ $is_first_backup -eq 1 ] && init_git $tar_path || {
  cd $tar_path;
  git add .;
  git commit -a -m " back up $time";
  git push;
  }


页: [1]
查看完整版本: 结合Git实现Mysql差异备份,可用于生产环境