查明文件是否在最近2分钟内被修改



在bash脚本中,我想检查文件是否在过去2分钟内发生了更改。

我已经发现我可以使用stat file.ext -c %y访问上次修改的日期。如何检查此日期是否超过两分钟?

我认为这会很有帮助,

find . -mmin -2 -type f -print

此外,

find / -fstype local -mmin -2

完成脚本以完成您想要的任务:

#!/bin/sh
# Input file
FILE=/tmp/test.txt
# How many seconds before file is deemed "older"
OLDTIME=120
# Get current and file times
CURTIME=$(date +%s)
FILETIME=$(stat $FILE -c %Y)
TIMEDIFF=$(expr $CURTIME - $FILETIME)
# Check if file older
if [ $TIMEDIFF -gt $OLDTIME ]; then
   echo "File is older, do stuff here"
fi

如果使用macOS,请使用stat -t %s -f %m $FILE代替FILETIME,如Alcanzar的注释所示。

这里有一个更简单的版本,它在expr:上使用shell数学

秒(创意)

echo $(( $(date +%s) - $(stat file.txt  -c %Y) ))

分钟(用于回答)

echo $(( ($(date +%s) - $(stat file.txt  -c %Y)) / 60 ))

小时

echo $(( ($(date +%s) - $(stat file.txt  -c %Y)) / 3600 ))

我通过这种方式解决了这个问题:获取文件的当前日期和上次修改日期(均为unix时间戳格式)。从当前日期减去修改后的日期,并将结果除以60(将其转换为分钟)。

expr $(expr $(date +%s) - $(stat mail1.txt -c %Y)) / 60

也许这不是最干净的解决方案,但效果很好。

以下是我的操作方法:(我会使用一个合适的临时文件)

touch -d"-2min" .tmp
[ "$file" -nt .tmp ] && echo "file is less than 2 minutes old"

对于那些偶尔喜欢1行的人:

test $(stat -c %Y -- "$FILE") -gt $(($EPOCHSECONDS - 120))

该解决方案对任何类型的文件名都是安全的,包括它是否包含%!"`' ()

这里有一个解决方案,可以测试文件是否早于X秒。它不使用具有特定平台语法的stat,也不使用粒度不超过1分钟的find

interval_in_seconds=10
filetime=$(date -r "$filepath" +"%s")
now=$(date +"%s")
timediff=$(expr $now - $filetime)
if [ $timediff -ge $interval_in_seconds ]; then
  echo ""
fi

最新更新