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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32019432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:03:44  来源:igfitidea点击:

If file modification date is older than N days

bash

提问by Ray

This question pertains to taking action if a file has a modification date older than so many days. I'm sure it would be similar for creation date or access date, but for modification date, if I have:

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

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

How would I do:

我该怎么做:

if file modification time is older than N days
then
fi

回答by Charles Duffy

Several approaches are available. One is just to ask findto do the filtering for you:

有几种方法可用。一种是要求find为您做过滤:

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


Another is to use GNU date to do the math:

另一种方法是使用 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


If you have GNU stat, you can ask for a file's timestamp in seconds-since-epoch, and do some math yourself (though this will potentially be a bit off on the boundary cases, since it's counting seconds -- and not taking into account leap days and such -- and not rounding to the beginning of a day):

如果你有 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


Another option, if you need to support non-GNU platforms, is to shell out to Perl (which I'll leave it to others to demonstrate).

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

If you're interested more generally in getting timestamp information from files, and portability and robustness constraints surrounding same, see also BashFAQ #87.

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