Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining age of a file in shell script

Tags:

file

shell

unix

G'day,

I need to see if a specific file is more than 58 minutes old from a sh shell script. I'm talking straight vanilla Solaris shell with some POSIX extensions it seems.

I've thought of doing a

touch -t YYYYMMDDHHmm.SS /var/tmp/toto

where the timestamp is 58 minutes ago and then doing a

find ./logs_dir \! -newer /var/tmp/toto -print

We need to postprocess some log files that have been retrieved from various servers using mirror. Waiting for the files to be stable is the way this team decides if the mirror is finished and hence that day's logs are now complete and ready for processing.

Any suggestions gratefully received.

cheers,

like image 616
Rob Wells Avatar asked Jun 09 '09 11:06

Rob Wells


3 Answers

This is now an old question, sorry, but for the sake of others searching for a good solution as I was...

The best method I can think of is to use the find(1) command which is the only Un*x command I know of that can directly test file age:

if [ "$(find $file -mmin +58)" != "" ]
then
  ... regenerate the file ...
fi

The other option is to use the stat(1) command to return the age of the file in seconds and the date command to return the time now in seconds. Combined with the bash shell math operator working out the age of the file becomes quite easy:

age=$(stat -c %Y $file)
now=$(date +"%s")
if (( (now - age) > (58 * 60) ))
then
    ... regenerate the file ...
fi

You could do the above without the two variables, but they make things clearer, as does use of bash math (which could also be replaced). I've used the find(1) method quite extensively in scripts over the years and recommend it unless you actually need to know age in seconds.

like image 56
Brian C Avatar answered Sep 21 '22 23:09

Brian C


I needed something to test age of a specific file, to not re-download too often. So using GNU date and bash:

# if file's modtime hour is less than current hour:
[[ $(date +%k -r GPW/mstall.zip) -lt $(date +%k) ]] && \
wget -S -N \
http://bossa.pl/pub/metastock/mstock/mstall.zip \

Update--this version works much better for me, and is more accurate and understandable:

[[ $(date +%s -r mstall.zip) -lt $(date +%s --date="77 min ago") ]] && echo File is older than 1hr 17min

The BSD variant (tested on a Mac) is:

[[ $(stat -f "%m" mstall.zip) -lt $(date -j -v-77M +%s) ]] && echo File is older than 1hr 17min
like image 25
Marcos Avatar answered Sep 19 '22 23:09

Marcos


You can use different units in the find command, for example:

find . -mtime +0h55m

Will return any files with modified dates older than 55 minutes ago.

like image 42
alxp Avatar answered Sep 20 '22 23:09

alxp