Linux计划任务通过执行脚本…

来源:互联网 发布:php用来做什么的 编辑:程序博客网 时间:2024/06/10 06:45
原文地址:Linux计划任务通过执行脚本备份XAMPP安装的MySQL数据库作者:邓强
1. 首先编辑计划任务
# vim /etc/crontab  加入以下代码:
# mysqldump mysqlbases to thisfile
0 2 * * * root/usr/bin/mysqlbak
这是设置每天2点定时执行mysqlbak文件,mysqlbak是一个脚本文件,下面会写到其中内容。

2.创建mysql数据库备份到的文件夹并给予此文件夹写入的权限
#mkdir /home/mysqldatabak
# chmod -R 777/home/mysqldatabak

3. 创建shell脚本文件mysqlbak
# vi /usr/bin/mysqlbak

并将以下内容编辑到此脚本文件中
#!/bin/sh
# mysql_backup.sh: backup mysql databasesand keep newest 5 days backup.
#
# your mysql logininformation
# db_user is mysql username
# db_passwd is mysqlpassword
# db_host is mysql host
#-----------------------------
db_user="root"
db_passwd="123456"
db_host="localhost"
# the directory for story your backupfile.
backup_dir="/home/mysqldatabak"
# date format for backup file(dd-mm-yyyy)
time="$(date +"%Y-%m-%d")"
# mysql, mysqldump and some other bin'spath
MYSQL="/opt/lampp/bin/mysql"
# "$(which mysql)"
MYSQLDUMP="/opt/lampp/bin/mysqldump"
#"$(which mysqldump)"
MKDIR="$(which mkdir)"
RM="$(which rm)"
MV="$(which mv)"
GZIP="$(which gzip)"
# check the directory for store backup iswriteable
test ! -w $backup_dir&& echo "Error: $backup_dir isun-writeable." && exit0
# the directory for story the newestbackup
test ! -d "$backup_dir/backup.0/"&& $MKDIR"$backup_dir/backup.0/"

# get all databases
all_db="$($MYSQL -u$db_user -h$db_host-p$db_passwd -Bse 'show databases')"

for db in $all_db
do
$MYSQLDUMP -u $db_user -h $db_host-p$db_passwd $db | $GZIP -9 >"$backup_dir/backup.0/$time.$db.gz"
done
# delete the oldest backup
test -d "$backup_dir/backup.5/"&& $RM -rf"$backup_dir/backup.5"
# rotate backup directory
for int in 4 3 2 1 0
do
if(test -d"$backup_dir"/backup."$int")
then
  next_int=`expr $int + 1`
   $MV"$backup_dir"/backup."$int""$backup_dir"/backup."$next_int"
fi
done

exit 0;

4.  
给/usr/bin/mysqlbak脚本可执行的权限
# chmod +x /usr/bin/mysqlbak
最后重启计划任务   service crondrestart

5. 这样在/home/mysqldatabak/ 每天的凌晨2时会自动运行此脚本,然后备份数据库到此目录。如下图所示则说明备份成功:
<1>

[转载]Linux计划任务通过执行脚本备份XAMPP安装的MySQL数据库
<2>

[转载]Linux计划任务通过执行脚本备份XAMPP安装的MySQL数据库


本文修改自:http://www.wangjunfeng.com.cn/archives/243.html
0 0