如何在 bash 中检查一个文件是否创建超过 x 时间以前?

我想在 linux bash 中检查一个文件是否创建的时间超过了 x。

假设文件名为 text.txt,时间为2小时。

 if [ what? ]
then
echo "old enough"
fi
122707 次浏览

创造时间并不存储。

存储的是三个时间戳(通常,它们可以在某些文件系统上关闭,也可以通过某些文件系统选项关闭) :

  • 最后访问时间
  • 最后修改时间
  • 最后一次换衣服了

对文件的“更改”被视为权限更改、重命名等,而修改只是内容。

考虑一下“ stat”工具的结果:

  File: `infolog.txt'
Size: 694         Blocks: 8          IO Block: 4096   regular file
Device: 801h/2049d  Inode: 11635578    Links: 1
Access: (0644/-rw-r--r--)  Uid: ( 1000/     fdr)   Gid: ( 1000/     fdr)
Access: 2009-01-01 22:04:15.000000000 -0800
Modify: 2009-01-01 22:05:05.000000000 -0800
Change: 2009-01-01 22:05:05.000000000 -0800

您可以在这里看到访问/修改/更改的三个日期 created date. You can only really be sure when the file contents were 被修改(“修改”字段)或其 inode 被更改(“更改”字段) 字段)。

Examples of when both fields get updated:

如果有人将额外信息连接到 文件的结尾。

如果有人通过 chmod 更改了权限,“更改”将被更新。

Only for modification time

if test `find "text.txt" -mmin +120`
then
echo old enough
fi

可以使用 -cmin进行更改,也可以使用 -amin进行访问时间。正如其他人指出的,我不认为你可以跟踪创造时间。

使用 stat来计算文件的最后修改日期,使用 date来计算当前时间和大量使用 bashism,人们可以根据文件的最后修改时间 1进行所需的测试。

if [ "$(( $(date +"%s") - $(stat -c "%Y" "$somefile") ))" -gt "7200" ]; then
echo "'$somefile' is older then 2 hours"
fi

While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)


  1. As Phil correctly noted creation time is not recorded, but use %Z instead of %Y below to get "change time" which may be what you want.

[更新]

For mac users, use stat -f "%m" "$somefile" instead of the Linux specific syntax above

虽然 ctime 不是 严格来说的创造时间,但它经常是。

Since ctime it isn't affected by changes to the contents of the file, it's usually only updated when the file is created. And yes - I can hear you all screaming - it's also updated if you change the access permissions or ownership... but generally that's something that's done once, usually at the same time you put the file there.

就我个人而言,我总是把时间用在所有事情上,我想这就是你想要的。但无论如何... 这里是 Guss 的“不吸引人”bash 的一个重新散列,它是一个易于使用的函数。

#!/bin/bash
function age() {
local filename=$1
local changed=`stat -c %Y "$filename"`
local now=`date +%s`
local elapsed


let elapsed=now-changed
echo $elapsed
}


file="/"
echo The age of $file is $(age "$file") seconds.

我一直喜欢用 date -r /the/file +%s来查找它的年龄。

您还可以执行 touch --date '2015-10-10 9:55' /tmp/file来获得任意日期/时间上的极细粒度时间。

Find one 很好,但我认为您可以使用其他方法,特别是如果您现在需要多少秒的文件旧

date -d "now - $( stat -c "%Y" $filename ) seconds" +%s

使用 GNU 日期

I use

file_age() {
local filename=$1
echo $(( $(date +%s) - $(date -r $filename +%s) ))
}


is_stale() {
local filename=$1
local max_minutes=20
[ $(file_age $filename) -gt $(( $max_minutes*60 )) ]
}


if is_stale /my/file; then
...
fi