在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
我用这种方式解决了问题:获取文件的当前日期和最后修改日期(均为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:
SECONDS(想法)
echo $(($(date +%s) - $(stat file.txt -c %Y)))
MINUTES(答案)
echo $(($(($(date +%s) - $(stat file.txt -c %Y))) / 60))