54

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

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
mboronin
  • 875
  • 1
  • 10
  • 16

3 Answers3

106

There is no simple command to get the time in seconds since a file was modified, but you can compute it from two pieces:

  • date +%s: the current time in seconds since the Epoch
  • date -r path/to/file +%s: the last modification time of the specified file in seconds since the Epoch

Use these values, you can apply simple Bash arithmetic:

lastModificationSeconds=$(date -r path/to/file +%s)
currentSeconds=$(date +%s)
((elapsedSeconds = currentSeconds - lastModificationSeconds))

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

echo $(($(date +%s) - $(date -r path/to/file +%s)))
janos
  • 120,954
  • 29
  • 226
  • 236
  • 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
  • 3
    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
  • Thanks @Timo, improved the post with that! – janos Dec 06 '22 at 19:15
11

In BASH, use this for seconds since last modified:

 expr `date +%s` - `stat -c %Y /home/user/my_file`
beroe
  • 11,784
  • 5
  • 34
  • 79
Jason Enochs
  • 1,436
  • 1
  • 13
  • 20
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,784
  • 5
  • 34
  • 79
  • 2
    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
  • 3
    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