bash 查看文件是否在过去 2 分钟内被修改
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28337961/
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
Find out if file has been modified within the last 2 minutes
提问by ph3nx
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
. How can I check if this date is older than two minutes?
我已经发现我可以使用stat file.ext -c %y
. 如何检查此日期是否早于两分钟?
回答by Skynet
I think this would be helpful,
我认为这会有所帮助,
find . -mmin -2 -type f -print
also,
还,
find / -fstype local -mmin -2
回答by Aubrey Kilian
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 的评论中所述。
回答by ph3nx
I solved the problem this way: get the current date and last modified date of the file (both in unix timestamp format). Subtract the modified date from the current date and divide the result by 60 (to convert it to minutes).
我通过这种方式解决了这个问题:获取文件的当前日期和上次修改日期(均采用 unix 时间戳格式)。从当前日期中减去修改日期并将结果除以 60(将其转换为分钟)。
expr $(expr $(date +%s) - $(stat mail1.txt -c %Y)) / 60
Maybe this is not the cleanest solution, but it works great.
也许这不是最干净的解决方案,但效果很好。
回答by nthnca
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"
回答by josh
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 ))
回答by Blago
Here is a solution that will test if a file is older than X seconds. It doesn't use stat
, which has platform-specific syntax, or find
which doesn't have granularity finer than 1 minute.
这是一个测试文件是否早于 X 秒的解决方案。它不使用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