linux - 如何在没有查找的情况下在 linux shell 脚本中根据日期查找和删除文件?

标签 linux bash shell

请注意我无法在目标环境中使用“查找”

我需要在 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/

相关文章:

linux - 从字符串中删除不需要的双引号

linux - 为 OS X 编译的 Golang 可执行扩展

linux - 如何在 Linux 服务器上找到 Perl 模块的位置?

Bash在执行前将引号插入字符串

linux - 如何使用 bash 脚本更改 iptable 条目?

regex - 使用 sed/awk/grep 格式化 git 日志输出

linux - 如何使用 linux 命令检查文件大小和文件数量?

linux - 使用 Git 时,什么时候用一个连字符 (-) 代替两个连字符 (--)?

linux - 拦截导出

linux - 回答终端查询并自动登录ssh