db_user="root" db_passwd="123456" db_host="localhost" backup_dir="/usr/local/apache2/htdocs/backup" time="$(date +"%Y%m%d%H%M")" MYSQL="/usr/local/mysql/bin/mysql" MYSQLDUMP="/usr/local/mysql/bin/mysqldump" MKDIR="/bin/mkdir" RM="/bin/rm" MV="/bin/mv" GZIP="/bin/gzip" test ! -w $backup_dir && echo "Error: $backup_dir is un-writeable." && exit 0 test ! -d "$backup_dir/$time" && $MKDIR -p "$backup_dir/$time" all_db="$($MYSQL -u $db_user -h $db_host -p$db_passwd -Bse 'show databases')"
for db in $all_db do $MYSQLDUMP "——default-character-set=gbk" -u $db_user -h $db_host -p$db_passwd $db | $GZIP -9 > "$backup_dir/$time/$db.gz" done exit 0;
设置定时任务
使用crontab -e命令编辑定时任务列表
[html] view plaincopyprint?
15 3 * * * sh /usr/scripts/mysql_backup.sh
表示每天凌晨3点15分执行该脚本进行数据库备份