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

Bash 如果文件修改日期早于N天,bash,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 +

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

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
#从纪元开始以秒为单位收集两次
百日前=$(日期-d'现在-100天+%s)
文件\时间=$(日期-r“$filename”+%s)
#…然后使用整数数学:

如果((file_time我很惊讶没有人提到这个方法-它就隐藏在
人工测试中,
-nt
-ot
,所以我怀疑它已经存在很长时间了:

N_DAYS_AGO=/tmp/n-days-ago.$$
touch -d "$N days ago" $N_DAYS_AGO
if [ "$myfile" -ot "$N_DAYS_AGO" ]; then
   ...
fi

bash本身并没有提供您所需要的工具——您还需要组件(比如
stat
find
)由您的操作系统提供。请将此问题更新为特定操作系统中的标记,以表明仅在GNU系统上使用答案是可以接受的,或者表明您需要与所有POSIX平台兼容。@Maheshkhavi,感谢您的更正,但请在元数据文本中保留编辑背后的理由,或者作为源代码中的隐藏注释(使用
语法);在帖子中用粗体字写出来可能会被认为是污损,这可能就是最初的建议被拒绝的原因。我很困惑:shebang?@flobee,shebang是UNIX上脚本顶部的一行,描述了运行它的解释器。例如,
!/bin/bash
是一个指定脚本的shebang可以使用bash运行,而
#!/bin/sh
允许使用任何POSIX sh解释器(可能不支持bash扩展)。@flobee,…也就是说,我看不到“shebang”这个词答案中的任何地方,所以我不太清楚混淆的来源。我问是因为一些snipet在bash中不起作用,无论如何,我在为我重新布线后得到了它,thx,shbang和bash版本…GNU bash给出了一些提示…:)
N_DAYS_AGO=/tmp/n-days-ago.$$
touch -d "$N days ago" $N_DAYS_AGO
if [ "$myfile" -ot "$N_DAYS_AGO" ]; then
   ...
fi