1 #!/bin/bash 2 #远程地址 3 dbhost='localhost' 4 #端口 5 dbport='3308' 6 #需要备份的数据库,多个数据库用空格分开 7 dbnames=("db1" "db2" "db3" "dd4 dd5") 8 #用户名 9 username='root' 10 #密码 11 password='password' 12 #备份时间 13 backtime=`date +%Y%m%d%H%M%S` 14 #日志备份路径 15 logpath='/www/mydata/log' 16 #数据备份路径 17 datapath='/www/mydata/mysql_bak' 18 19 for dbname in ${dbnames[@]}; do 20 #日志记录头部 21 echo "[${backtime}]-[${dbhost}]-[${dbport}]-备份数据库表${dbname}开始" >> ${logpath}/mysqllog.log 22 #正式备份数据库 23 for table in $dbname; do 24 source=`/www/mysql/bin/mysqldump --single-transaction -u${username} -p${password} -h${dbhost} -P${dbport} ${table}> ${datapath}/${dbname}_${backtime}.sql` 2>> ${logpath}/mysqllog.log; 25 #备份成功以下操作 26 if [ "$?" == 0 ];then 27 cd $datapath 28 #删除七天前备份,也就是只保存7天内的备份 29 find $datapath -name "*.sql" -type f -mtime +30 -exec rm -rf {} \; 30 echo "[${backtime}]-[${dbhost}]-[${dbport}]-备份数据库表${dbname}成功" >> ${logpath}/mysqllog.log 31 else 32 #备份失败则进行以下操作 33 echo "[${backtime}]-[${dbhost}]-[${dbport}]-备份数据库表${dbname}失败" >> ${logpath}/mysqllog.log 34 fi 35 done 36 done
设置文件成可执行的
chmod u+x full.sh
# 编辑定时任务
crontab -e
30 23 * * * /www/back.sh
重启,不重启不会生效
service crond stop //关闭服务
service crond restart //重启服务
service crond status //查看服务状态
如果提示:mysqldump 找不到,则建立一个软连接
或者像上文指定具体路径
ln -s /usr/local/mysql/bin/mysql /usr/bin/mysql
ln -s /usr/local/mysql/bin/mysqldump /usr/bin/mysqldump
如果mysql是自定义安装,且不在默认目录时,会提示
Can't connect to local MySQL server through socket '/tmp/mysql.sock' (111)
同样建立一个软连接搞定
ln -s /usr/local/mysql/mysql.sock /var/mysql.sock
如果当前用户没有操作权限,则把文件夹给他得了,嘿嘿:
chown -R mysql:mysql /www/mydata
标签:bin,www,centos,备份,mySQL,数据库,mysql,dbname From: https://www.cnblogs.com/jamin/p/18583492