How to get time since file was last modified in seconds with bash?

I need to get the time in seconds since a file was last modified. ls -l doesn't show it.


The GNU implementation of date has an -r option to print the last modification date of a file instead of the current date. And we can use the format specifier %s to get the time in seconds, which is convenient to compute time differences.

lastModificationSeconds=$(date +%s -r file.txt)
currentSeconds=$(date +%s)

And then you can use arithmetic context to compute the difference, for example:

((elapsedSeconds = currentSeconds - lastModificationSeconds))
# or
elapsedSeconds=$((currentSeconds - lastModificationSeconds))

You could also compute and print the elapsed seconds directly without temporary variables:

echo $(($(date +%s) - $(date +%s -r file.txt)))

Unfortunately the BSD implementation of date (for example in Mac OS X) doesn't support the -r flag. To get the last modification seconds, you can use the stat command instead, as other answers suggested. Once you have that, the rest of the procedure is the same to compute the elapsed seconds.


I know the tag is Linux, but the stat -c syntax doesn't work for me on OSX. This does work...

echo $(( $(date +%s) - $(stat -f%c myfile.txt) ))

And as a function to be called with the file name:

lastmod(){
     echo "Last modified" $(( $(date +%s) - $(stat -f%c "$1") )) "seconds ago"
}

In BASH, use this for seconds since last modified:

 expr `date +%s` - `stat -c %Y /home/user/my_file`