31

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?

ph3nx
  • 1,026
  • 2
  • 12
  • 25

7 Answers7

30

I think this would be helpful,

find . -mmin -2 -type f -print

also,

find / -fstype local -mmin -2
Arnab Nandy
  • 6,472
  • 5
  • 44
  • 50
28

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.

Leo K
  • 5,189
  • 3
  • 12
  • 27
Aubrey Kilian
  • 316
  • 2
  • 3
12

Here's an even simpler version that uses shell math over 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 ))
Shahzaib Sheikh
  • 647
  • 1
  • 9
  • 21
josh
  • 438
  • 4
  • 10
10

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.

ph3nx
  • 1,026
  • 2
  • 12
  • 25
10

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"
nthnca
  • 101
  • 1
  • 2
3

For those who like 1-liners once in a while:

test $(stat -c %Y -- "$FILE") -gt $(($EPOCHSECONDS - 120))

This solution is also safe with any kind of file name, including if it contains %!"`' ()

VasiliNovikov
  • 9,681
  • 4
  • 44
  • 62
2

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.

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
Blago
  • 4,697
  • 2
  • 34
  • 29