Determining age of a file in shell script

后端 未结 6 1132
暖寄归人
暖寄归人 2021-01-04 18:28

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 i

6条回答
  •  灰色年华
    2021-01-04 18:50

    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.

提交回复
热议问题