Linux定时删除文件

#!/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脚本编写的语法

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值