如果文件的修改日期早于这么多天,则此问题适用于采取措施。我确定它与创建日期或访问日期类似,但对于修改日期,如果我有:
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日期来做数学:
# 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发送shell(我将把它留给其他人来演示)。
如果您更感兴趣的是从文件中获取时间戳信息,以及相同的可移植性和稳健性约束,请参阅BashFAQ #87。