1、回到根目录:cd /
2、创建文件夹:mkdir bak
3、进入bak文件夹:cd /bak
4、创建bakmysql文件夹:mkdir bakmysql
5、创建bakmysqlold文件夹:mkdir bakmysqlold
6、创建backup.sh文件:touch backup.sh
7、backup.sh文件写入下面内容:
#!/bin/sh
cd /bak/bakmysql
echo "You are in bakmysql directory"
mv bakmysql* /bak/bakmysqlold
echo "Old databases are moved to bakmysqlold folder"
Now=$(date +"%d-%m-%Y")
File=bakmysql-$Now.sql
mysqldump -uroot -p'mypassword' test > $File
echo "Your database backup successfully completed"
SevenDays=$(date -d -7day +"%d-%m-%Y")
if [ -f /bak/bakmysqlold/bakmysql-$SevenDays.sql ]
then
rm -rf /bak/bakmysqlold/bakmysql-$SevenDays.sql
echo "You have delete 7days ago bak file "
else
echo "7days ago bak file not exist "
fi
8、把上面mysqldump -uroot -p'mypassword' test > $File这一句的mypassword修改为你的数据库登录密码,test修改为你的数据库名称,root修改为你的数据库登录账号。修改完后保存退出
9、运行 crontab -e,写入以下内容:
0 3 * * * /bin/bash /bak/backup.sh
保存退出,之后每天早上 3:00 就会自动备份数据库到bak目录下了。
查看规则是否已经添加进去命令:crontab -l