45

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

Eric Leschinski
  • 135,913
  • 89
  • 401
  • 325
mboronin
  • 737
  • 1
  • 8
  • 15

3 Answers3

96

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.

janos
  • 115,756
  • 24
  • 210
  • 226
  • And if you want to have it in milliseconds: `$(($(date +'%s%N' -r file.txt)/1000000))` – Yeti Feb 10 '17 at 10:53
  • 5
    If you move the format part as the last argument it works with macs too (at least with sierra). `date -r file.txt +%s` and `echo $(($(date +%s) - $(date -r file.txt +%s)))` – Timo Jan 15 '18 at 10:19
  • For folders and subfolders with multiple files use this in conjunction with https://stackoverflow.com/a/23034261/1707015 -- awesome :D – qräbnö Jul 26 '18 at 17:12
  • 1
    MacOS supports `date -r` so long as you use it in this order: `date -r file.txt +%s` – diachedelic Feb 06 '20 at 07:28
10

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"
}
beroe
  • 11,052
  • 4
  • 32
  • 79
  • Maybe that used to work under OS X, but now `-f%c` gives an error. Using `stat -c%Y "$1"` works. – Brent Faust Oct 02 '15 at 00:10
  • 1
    @BrentFoust Still works from me with 10.10.5 (and `-c%Y` doesn't). Are you on El Capitan? – beroe Oct 06 '15 at 01:59
  • 2
    At least on sierra the "linux" way would otherwise work just fine, but it just doesn't like the ordering of the params. It only accepts the format as the last argument. So `date -r file.txt +%s` works for me and it also seems to work for some linuxes, but obviously it's not POSIX so portability is dubious.. – Timo Jan 15 '18 at 10:15
8

In BASH, use this for seconds since last modified:

 expr `date +%s` - `stat -c %Y /home/user/my_file`
beroe
  • 11,052
  • 4
  • 32
  • 79
Jason Enochs
  • 1,380
  • 1
  • 12
  • 19