MENU

一个MySQL简单备份脚本

November 14, 2022 • Linux运维工作

由于很多项目部署,需要使用MySQL备份脚本,有时候一个数据库下面有多个数据库,就写了一个简单的逻辑备份排除系统默认库的全量数据库的脚本。

#!/bin/bash
DATE=`date +"%Y%m%d"`
host='127.0.0.1'
port='3306'
user='*****'
passWord='******'
databaseBundle=`mysql -h $host -P $port  -u$user -p$passWord  -e 'show databases;'`
if [ $? -ne 0 ];then
   echo '数据库连接异常退出!'
   exit
fi
for data in $databaseBundle;
do
  # 几个判断排除系统自带库
  if [ $data == 'Database' ];then
     continue
  elif [ $data == 'information_schema' ];then
     continue
  elif [ $data == 'mysql' ];then
     continue
  elif [ $data == 'performance_schema' ];then
     continue
  elif [ $data == 'sys' ];then
     continue
  else
     echo $data
     mysqldump -h $host -P $port  -u$user -p$passWord --databases ${data}>/mysql-bak/mysql-${data}-$DATE.sql
     if [ $? -ne 0 ];then
        echo '数据库备份异常退出!'
        # 删除错误备份的空sql
        rm -f /mysql-bak/mysql-${data}-$DATE.sql
        continue
     fi
     # 保留最新的30份备份
     find /mysql-bak/ -type f -name "mysql-${data}*.sql" | sort -nr | awk '{if (NR>30){print $1}}' | xargs rm -f
  fi
done