[英]modifying atime to check if file has been modified within last 24 hours
[英]Find out if file has been modified within the last 2 minutes
在 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
for FILETIME
,如 Alcanzar 的评论中所述。
我通过这种方式解决了这个问题:获取文件的当前日期和上次修改日期(均采用 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"
这是一个更简单的版本,它使用 shell 数学而不是 expr:
秒(想法)
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 ))
这是一个测试文件是否早于 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
对于那些偶尔喜欢 1-liners 的人:
test $(stat -c %Y -- "$FILE") -gt $(($(date +%s) - 120))
此解决方案对于任何类型的文件名也是安全的,包括它是否包含%!"`' ()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.