简体   繁体   English

查看文件是否在过去 2 分钟内被修改

[英]Find out if file has been modified within the last 2 minutes

In a bash script I want to check if a file has been changed within the last 2 minutes.在 bash 脚本中,我想检查文件是否在过去 2 分钟内被更改。

I already found out that I can access the date of the last modification with stat file.ext -c %y .我已经发现我可以使用stat file.ext -c %y访问上次修改的日期。 How can I check if this date is older than two minutes?如何检查此日期是否超过两分钟?

I think this would be helpful,我认为这会有所帮助,

find . -mmin -2 -type f -print

also,还,

find / -fstype local -mmin -2

Complete script to do what you're after:完整的脚本来做你所追求的:

#!/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

If you're on macOS , use stat -t %s -f %m $FILE for FILETIME , as in a comment by Alcanzar.如果您使用的是macOS ,请使用stat -t %s -f %m $FILE for FILETIME ,如 Alcanzar 的评论中所述。

I solved the problem this way: get the current date and last modified date of the file (both in unix timestamp format).我通过这种方式解决了这个问题:获取文件的当前日期和上次修改日期(均采用 unix 时间戳格式)。 Subtract the modified date from the current date and divide the result by 60 (to convert it to minutes).从当前日期中减去修改日期并将结果除以 60(将其转换为分钟)。

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

Maybe this is not the cleanest solution, but it works great.也许这不是最干净的解决方案,但效果很好。

Here is how I would do it: (I would use a proper temp file)这是我的方法:(我会使用适当的临时文件)

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

Here's an even simpler version that uses shell math over expr:这是一个更简单的版本,它使用 shell 数学而不是 expr:

SECONDS (for idea)秒(想法)

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

MINUTES (for answer)分钟(用于回答)

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

HOURS小时

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

Here is a solution that will test if a file is older than X seconds.这是一个测试文件是否早于 X 秒的解决方案。 It doesn't use stat , which has platform-specific syntax, or find which doesn't have granularity finer than 1 minute.它不使用stat ,它具有特定于平台的语法,或find粒度不超过 1 分钟。

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

For those who like 1-liners once in a while:对于那些偶尔喜欢 1-liners 的人:

test $(stat -c %Y -- "$FILE") -gt $(($(date +%s) - 120))

This solution is also safe with any kind of file name, including if it contains %!"`' ()此解决方案对于任何类型的文件名也是安全的,包括它是否包含%!"`' ()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM