Difference between revisions of "Test file age"

From Noah.org
Jump to navigationJump to search
(New page: Category:Engineering 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...)
 
Line 3: Line 3:
  
 
<pre>
 
<pre>
 +
#!/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=`expr 60 \* 60 \* 24` # seconds in a day
 
MAXAGE=`expr 60 \* 60 \* 24` # seconds in a day
 
# file age in seconds = current_time - file_modification_time.
 
# file age in seconds = current_time - file_modification_time.
Line 8: Line 13:
 
test $FILEAGE -lt $MAXAGE && {
 
test $FILEAGE -lt $MAXAGE && {
 
     echo "$FILE is less than $MAXAGE seconds old."
 
     echo "$FILE is less than $MAXAGE seconds old."
 +
    exit 0
 
}
 
}
</pre>
+
echo "$FILE is older than $MAXAGE seconds."
 +
exit 1

Revision as of 19:34, 6 December 2007

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=`expr 60 \* 60 \* 24` # 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