centos7中用shell脚本实现mysql分库分表备份

环境:

centos7中用shell脚本实现mysql分库分表备份_第1张图片


脚本:

#!/bash/bin
back_path=/backup/db
databases_file=/backup/databases.list
[ -f $databases_file ] || touch /backup/databases.list
if [[ ! -s ${databases_file} ]]
then
	echo "$databases_file为空,请在该文件中写上需要备份的数据库名字(一个数据库占一行)"
  exit
fi

while :
do
read -p "input bak user and password: " user password
if [ -n "$user" ] && [ -n "$password" ]
then
  mysql -u${user} -p${password} -e "show databases" &> /dev/null
  if [ $? -eq 0 ]
  then
    echo "登录mysql成功!!!"
    break
  else
    echo "登录失败,请检查用户和密码是否输入正确!!!"
  fi
fi
done

while read line
do
  [ -d ${back_path}/$line ] || mkdir -p ${back_path}/$line
	mysqldump -u${user} -p${password} -B $line 2>/dev/null | gzip 1> ${back_path}/${line}/${line}_$(date +%F).sql.gz
  mysql -u$user -p$password -N -e "show tables from $line" 1> /backup/tbname 2>/dev/null
	while read tb
	do
		mysqldump -u${user} -p${password} $line $tb 2>/dev/null | gzip 1>${back_path}/$line/${line}_${tb}_$(date +%F).sql.gz
	done < /backup/tbname 
done < $databases_file
if [ $? -eq 0 ]
then
  echo "备份成功!!备份目录是$back_path"
else 
  echo "备份失败!!!请检查"
fi
rm -rf /backup/tbname 
true > $databases_file

 运行结果: 

centos7中用shell脚本实现mysql分库分表备份_第2张图片

你可能感兴趣的:(shell,mysql,数据库)