56

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

0

3 Answers 3

110

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)))
5
  • 1
    And if you want to have it in milliseconds: $(($(date +'%s%N' -r file.txt)/1000000))
    – Yeti
    Commented Feb 10, 2017 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
    Commented Jan 15, 2018 at 10:19
  • For folders and subfolders with multiple files use this in conjunction with stackoverflow.com/a/23034261/1707015 -- awesome :D
    – qräbnö
    Commented Jul 26, 2018 at 17:12
  • 3
    MacOS supports date -r so long as you use it in this order: date -r file.txt +%s Commented Feb 6, 2020 at 7:28
  • Thanks @Timo, improved the post with that!
    – janos
    Commented Dec 6, 2022 at 19:15
12

In BASH, use this for seconds since last modified:

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

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"
}
3
  • 2
    Maybe that used to work under OS X, but now -f%c gives an error. Using stat -c%Y "$1" works. Commented Oct 2, 2015 at 0:10
  • 1
    @BrentFoust Still works from me with 10.10.5 (and -c%Y doesn't). Are you on El Capitan?
    – beroe
    Commented Oct 6, 2015 at 1:59
  • 4
    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
    Commented Jan 15, 2018 at 10:15

Not the answer you're looking for? Browse other questions tagged or ask your own question.