how to use shell script checking last changed time of a file
You can get the last modification time of a file with stat
, and the current date with date
. You can use format strings for both to get them in "seconds since the epoch":
current=`date +%s`last_modified=`stat -c "%Y" $file`
Then, it's pretty easy to put that in a condition. For example:
if [ $(($current-$last_modified)) -gt 180 ]; then echo "old"; else echo "new"; fi
The syntax of this if statement depends on your particular shell, but the date commands don't. I use bash; modify as necessary.
if [ $(( $(date +%s) - $(date +%s -r <file>) )) -le 180 ]; then # was modified in last three minuteselse # was not modified in last three minutesfi
The +%s
tells date to output a UNIX time (the important bit is that it's an integer in seconds). You can also use stat to get this information - the command stat -c %Y <file>
is equivalent. Make sure to use %Y
not %y
, so that you get a usable time in seconds.