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

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

Posted by: admin January 30, 2018 Leave a comment

Questions:

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 stat file.ext -c %y. How can I check if this date is older than two minutes?

Answers:

I think this would be helpful,

find . -mmin -2 -type f -print

also,

find / -fstype local -mmin -2

Questions:
Answers:

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

Questions:
Answers:

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).

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

Maybe this is not the cleanest solution, but it works great.