背景
数据库备份文件每天生成一个,但要求只保留最近一周的备份文件,所以通过定时任务删除
过期的文件
实现方式
通过crontab定时任务,每天执行一次任务,将过期的数据文件删除
定时任务
15 0 * * * deletefiles.sh --dataPath=/opt/mysql --dateTime=7 --fileName=*.sql >> /var/log/deletefiles.log
实现文件deletefiles.sh
#!/bin/bash
#current_path=`pwd`
case "`uname`" in
Linux)
bin_absolute_path=$(readlink -f $(dirname $0))
;;
*)
bin_absolute_path=`cd $(dirname $0);pwd`
;;
esac
getopt_cmd=$(getopt -n $(basename $0) -o u: --long dataPath:,dateTime:,fileName: -- "$@")
[ $? -ne 0 ] && exit 1
eval set -- "$getopt_cmd"
userName=`whoami`
if [ $userName == "root" ];then
echo -e "\e[33minstall check...\e[0m"
else
echo -e "\e[33muser is $userName,you should be root\e[0m"
exit
fi
PRGDIR=`dirname "$PRG"`
HOME_PATH=$(cd $(dirname $0)/ && pwd)
data_path="${HOME_PATH}"
date_time="7"
function deletefiles(){
if [ -z "${data_file}" ];then
usage
fi
local currentDate=`date +%s`
echo "current date is:" $currentDate
for file in `find ${data_path} -name ${data_file}`;do
local name=$file
local modifyDate=$(stat -c %Y $file)
local existTime=$[$currentDate-$modifyDate]
local existTime=$[$existTime/86400]
if [ $existTime -gt $date_time ];then
echo "file:" $name "modify Date:" $modifyDate + "Exist time:" $existTime + "Delete:yes"
rm -rf $file
else
echo "file:" $name "modify Date:" $modifyDate + "Exist time:" $existTime + "Delete:no"
fi
done
}
function create(){
echo -e "\033[33m...\033[0m"
}
function usage(){
echo "usage: tools [--options <string>] [show]
-u 用户默认为当前登录用户
--dataPath <string> 数据文件路径,默认当前路径
--dateTime <string> 指定日期,默认7d
--fileName <string> 指定文件名称,例: --fileName=abc*.zip
deletefiles 删除指定日期前文件,例: deletefiles --dataPath=/opt --dateTime=7 --fileName=aa*.zip
"
exit
}
function starts(){
case "$1" in
deletefiles) deletefiles ;;
*) usage ;;
esac
}
function init(){
while [ -n "$1" ];do
case "$1" in
-u) userName="$2" ;shift ;;
--dataPath) data_path="$2" ;shift ;;
--dateTime) date_time="$2" ;shift ;;
--fileName) data_file="$2" ;shift ;;
*) starts $2 ;shift ;;
esac
shift
done
}
if [ "$#" -gt 1 ];then
init $*
else
usage
fi