请注意,我不能在目标环境中使用'find'
我需要删除所有文件超过7天旧的Linux shell脚本。比如说:
FILES=./path/to/dir
for f in $FILES
do
echo "Processing $f file..."
# take action on each file. $f store current file name
# perhaps stat each file to get the last modified date and then delete files with date older than today -7 days.
done
我可以用“stat”来做这个吗?我试图使用
find *.gz -mtime +7 -delete
但是发现我不能在目标系统上使用find(cron用户没有权限,这不能更改)。目标系统是红帽企业号
文件名的格式如下:
gzip > /mnt/target03/rest-of-path/web/backups/DATABASE ENAME_ date "+%Y-%m-%d"
.gz
4条答案
按热度按时间9lowa7mx1#
这应该是可行的:
一点解释:
stat <file> -c '%Z'
给出文件的修改时间,单位为自文件的UNIX纪元以来的秒数,$(date +%s)
给出当前UNIX时间戳。然后只需简单地检查文件的时间戳加上30天的秒数是否大于当前时间戳。1l5u6lss2#
因为你在文件名中有时间,然后使用它来计时删除,这里有一些代码可以做到这一点:
此脚本获取自epoch以来的当前时间(以秒为单位),然后计算7天前的时间戳。然后为每个文件解析文件名,并将每个文件名中嵌入的日期转换为时间戳,然后比较时间戳以确定要删除哪些文件。使用时间戳摆脱了直接处理日期的所有麻烦(闰年,月份中的不同日期等)
实际的删除被注解掉了,这样您就可以测试代码了。
mznpcxlj3#
如果你喜欢依赖文件名中的日期,你可以使用这个例程,检查一个日期是否比另一个日期早:
然后你可以遍历文件名,传递'-7 days'作为第二个日期:
在
is_older
例程中,date -d "-7 days" +%Y%m%d
将以数字格式返回7天前的日期,以供比较。b4lqfgs44#
做