Test a file date with bash

JeffPHP picture JeffPHP · Nov 30, 2009 · Viewed 22.2k times · Source

I am trying to test how old ago a file was created (in seconds) with bash in an if statement. I need creation date, not modification.

Do you have any idea how to do this, without using a command like find with grep?

Answer

Joel picture Joel · Nov 30, 2009

I'm afraid I cann't answer the question for creation time, but for last modification time you can use the following to get the epoch date, in seconds, since filename was last modified:

date --utc --reference=filename +%s

So you could then so something like:

modsecs=$(date --utc --reference=filename +%s)
nowsecs=$(date +%s)
delta=$(($nowsecs-$modsecs))
echo "File $filename was modified $delta secs ago"

if [ $delta -lt 120 ]; then
  # do something
fi

etc..

Update A more elgant way of doing this (again, modified time only): how do I check in bash whether a file was created more than x time ago?