请注意我无法在目标环境中使用“查找”
我需要在 linux shell 脚本中删除超过 7 天的所有文件。类似于:
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用户没有权限,无法更改)。目标系统是 Redhat Enterprise。
文件名的格式如下:
gzip >/mnt/target03/rest-of-path/web/backups/DATABASENAME_date "+%Y-%m-%d"
.gz
最佳答案
这应该有效:
#!/bin/sh
DIR="/path/to/your/files"
now=$(date +%s)
DAYS=30
for file in "$DIR/"*
do
if [ $(((`stat $file -c '%Y'`) + (86400 * $DAYS))) -lt $now ]
then
# process / rm / whatever the file...
fi
done
一些解释:stat <file> -c '%Z'
给出文件自 UNIX 纪元以来的秒数修改时间,以及 $(date +%s)
给出当前的 UNIX 时间戳。然后只需简单检查一下文件的时间戳加上 7 天的秒数是否大于当前时间戳。
关于linux - 如何在没有查找的情况下在 linux shell 脚本中根据日期查找和删除文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8593171/