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