Take action only if a file is X hours (or seconds) old

shell: #!/bin/ash

I searched and found a few relevant posts (here and here - both by porter, on the same day (?)) however both are just a do while loop, I need to check a file date and compare it to the current time.

I would like it to say if file 'test' is more than 12 hours old than "right now" to echo back "file is stale" else echo "file is ok". I was thinking I could get the "unix time" of the file and just subtract them, but honestly I have no idea how to get the unix time of a file (much less in a script)

concept:

touch magic

$timediff = creation time of file magic - creation time of file test (in seconds)

if $timediff > 43200 (seconds) then echo "file is stale" else "file is ok"

I'm sure there is a better/easier way to do this... Thanks all!

I'm not an ash coder. However

# the last time a file was changed in epoch seconds
perl -e '@arr=stat $ARGV[0]; print "$arr[9]\n" '  filename
# now in epoch seconds
perl -e ' $now=time; print "$now\n" '
# therefore: now - filetime == age of file in seconds
perl -e '@arr=stat $ARGV[0];  $diff = time - $arr[9];  print "$diff\n" '  filename

There are less readable more compact ways to write the code, but this works for starters.

If you have GNU date on your system something similar is possible.

I have gnu ls (coreutils) 5.2.1 and this works for me:

ls -l --time-style='+%s' magic | awk '{print $6}'

current time is:

date +%s

and math comparison as necessary.

jim mcnamara & peterro, thank you for responding.

jim: I would like to avoid perl if possible... (this is running on a router with openwrt - low powered)

peterro: I'm using BusyBox v1.13.4, which does not recognize the --time-style for ls. Obviously, the

date +%s

works fine.

Any other suggestions?

---------- Post updated at 10:03 PM ---------- Previous update was at 06:57 PM ----------

Looking around in some unix books I found

find -printf %A_@

but unfortunately, -printf isn't recognized in the shell I'm using...

---------- Post updated at 10:39 PM ---------- Previous update was at 10:03 PM ----------

Thank you so much for saying this...

date +%s -r test

Gives me exactly what I need. I wonder why GNU date is included, but ls isn't?

Oh well. Thanks for the feedback!!