Test file age

From Noah.org
Revision as of 19:39, 6 December 2007 by Root (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This shows how to check if a file is older than a given date using Bash. I use this to test the age of my server backup log. If the log is more than a day old then I send an alert.

#!/bin/sh
# This checks that the specified file is less than 24 hours old.
# returns 0 if younger than 24 hours.
# returns 1 if older than 24 hours.
FILE=/home/backup/BACKUP_TIMESTAMP
MAXAGE=$(bc <<< '24*60*60') # seconds in a day
# file age in seconds = current_time - file_modification_time.
FILEAGE=$(($(date +%s) - $(stat -c '%Y' "$FILE")))
test $FILEAGE -lt $MAXAGE && {
    echo "$FILE is less than $MAXAGE seconds old."
    exit 0
}
echo "$FILE is older than $MAXAGE seconds."
exit 1