#!/bin/sh
data_path="/opt/gaofan"
expire_time=1 # 设置删除间隔时间,这里删除一天前的文件
deletefiles(){
local currentDate=`date +%s`
echo "current date is:" $currentDate
for file in `find $1 -name "*.txt"` # 设置删除什么样的文件,这里删除后缀为txt的所有文件
do
local name=$file
local modifyDate=$(stat -c %Y $file)
echo "modify date is:" $modifyDate
local existTime=$[$currentDate - $modifyDate]
echo "exist date is:" $existTime
existTime=$[$existTime/86400]
echo "exist date is:" $existTime
if [ $existTime -gt $expire_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
}
deletefiles $data_path
vi编辑器创建delete.sh脚本
crontab -e进入编辑模式设置定时时间
* * * * * sh /opt/gaofan/delete.sh
为了快速验证,设置每天每分钟触发脚本,具体时间设置可以看crontab设置定时器时间
这里需要切换root用户,因为删除命令有时有权限,普通用户可能无法删除成功。
还有一点是需要注意shell脚本编写的语法