脚本如下
#!/bin/sh
#备份目录
dic="/usr/share/db_bak"
y=$(date +%Y)
m=$(date +%m)
d=$(date +%d)
#read -p "dbname:" dbname
#if [ ! -n "$dbname" ];then
# echo "not set dbname"
# exit
#fi
dbname="myfee"
#mysql备份文件名
filename=$dic/$dbname$y$m$d.sql
echo "bakup name:"$filename
#删除7天前的备份文件
for file in `ls -a $dic`
do
find -mtime 7 -name "*.tar" -exec rm -rf {} \;
done
#备份数据库
echo "备份数据库"
mysqldump -uroot -pxytkj123456654321 $dbname > $filename
dbname为数据库名
注意授权chmod a+x 脚本文件
通过crontab -e 设置定时任务,举例如下
00 02 * * * /usr/share/sh/db_bak.sh >> /var/log/db_back.log