bash - 如果文件修改日期早于 N 天

标签 bash

此问题涉及在文件的修改日期早于这么多天时采取的措施。我确定创建日期或访问日期会类似,但对于修改日期,如果我有:

file=path-name-to-some-file
N=100  # for example, N is number of days

我会怎么做:

if file modification time is older than N days
then
fi

最佳答案

有几种方法可用。一种是让 find 为您进行过滤:

if [[ $(find "$filename" -mtime +100 -print) ]]; then
  echo "File $filename exists and is older than 100 days"
fi

另一种是使用 GNU date 来做数学运算:

# collect both times in seconds-since-the-epoch
hundred_days_ago=$(date -d 'now - 100 days' +%s)
file_time=$(date -r "$filename" +%s)

# ...and then just use integer math:
if (( file_time <= hundred_days_ago )); then
  echo "$filename is older than 100 days"
fi

如果你有 GNU stat,你可以要求一个文件的时间戳,以秒为单位,从纪元开始,然后自己做一些数学运算(尽管这在边界情况下可能有点偏离,因为它计算的是秒——而不是考虑到闰日等——而不是四舍五入到一天的开始):

file_time=$(stat --format='%Y' "$filename")
current_time=$(( date +%s ))
if (( file_time < ( current_time - ( 60 * 60 * 24 * 100 ) ) )); then
  echo "$filename is older than 100 days"
fi

如果您需要支持非 GNU 平台,另一种选择是使用 Perl(我将留给其他人来演示)。

如果您对从文件中获取时间戳信息以及相关的可移植性和稳健性约束更感兴趣,另请参阅 BashFAQ #87 .

关于bash - 如果文件修改日期早于 N 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32019432/

相关文章:

bash - 将文本从先前的标准输出拉到命令行上

javascript - 如何使用大括号通过 "shelljs"在单个命令中创建多个目录?

linux - 我的 bash 脚本 (linux) 中的错误计数器在 while 语句期间不计数

python - 如何在 papermill 中参数化 Python 字典?

bash - 为什么用 "envsubst <file >file"重写一个文件会留空?

bash - 为什么 awk 不在这里创建文件?

linux - 一起计算 n 行的平均值

linux - git clone 和 cd 进去

bash - 如何在 bash 循环中组合两个范围?

bash - 跨多个目录同步文件修改时间