SQL_CMD="/www/server/mysql/bin/mysqldump" SQL_HOST="IP" SQL_USR="root" SQL_PWD="密码" SQL_DB="数据库名称" SQL_DIR="/www/backup/database/`date +%y%m%d`" #判断是否为root用户 if [ $UID -ne 0 ];then echo "only use root to exec." exit fi #判断该路径是否存在,不存在就创建一个 if [ ! -d $SQL_DIR ];then mkdir -p $SQL_DIR fi #备份数据库 $SQL_CMD -h$SQL_HOST -u$SQL_USR -p$SQL_PWD $SQL_DB >$SQL_DIR/$SQL_DB.sql #判断是否备份成功,成功打印出来路径 if [ $? -eq 0 ];then echo "Backup mysql already successful." echo "Backup path:$SQL_DIR" else echo "Backup mysql failed." fi #删除30天以前的备份文件 cd $SQL_DIR/../ ; find . -mtime +30 -exec rm -rf {} ; echo "Done" #把脚本加到crontab任务计划里 grep "mysql" /var/spool/cron/root >> /dev/null if [ $? -ne 0 ];then echo "0 0 * * * /bin/bash /root/shell/mysql.sh > /tmp/mysql.log 2>&1" >>/var/spool/cron/root /etc/init.d/crond restart fi