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

前端 未结 6 1723
栀梦
栀梦 2020-12-11 14:51

In a bash script I want to check if a file has been changed within the last 2 minutes.

I already found out that I can access the date of the last modification with <

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-11 15:09

    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.

提交回复
热议问题