Getting file age in a simple way

Uncategorized 0 Comments

I just needed a way to detect regularly if a file has been changed recently. The solution I came up with was this:

now=`date +%s`
mtime=`stat -c %Z /some/file`
if [ $((now - mtime)) -gt 3600 ]; then
    echo "xy seems to be out-of-date."
fi

This checks the current time and the modification time of the file, calculates the difference and checks if that’s greater than 3600 seconds (1 hour), then echoes something if it is greater.

This can be written in a more simplest way:

[ $((`date +%s` - `stat -c %Z /some/file`)) -gt 3600 ] &&
    echo "xy seems to be out-of-date."

This way you can easily put it in cron, like this, so it is checked twice a day:

0 9,21 * * * user [ $((`date +%s` - `stat -c %Z /some/file`)) -gt 3600 ] &&
    echo "xy seems to be out-of-date."

You can remove the “” at the end of the lines and write the commands in one line. BUT the “”s before the “%” have to be there to maintain proper escaping!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.