I need to get the time in seconds since a file was last modified. ls -l
doesn't show it.
3 Answers
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 Epochdate -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)))
-
1And if you want to have it in milliseconds:
$(($(date +'%s%N' -r file.txt)/1000000))
– YetiCommented Feb 10, 2017 at 10:53 -
5If you move the format part as the last argument it works with macs too (at least with sierra).
date -r file.txt +%s
andecho $(($(date +%s) - $(date -r file.txt +%s)))
– TimoCommented 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
-
3MacOS supports
date -r
so long as you use it in this order:date -r file.txt +%s
Commented Feb 6, 2020 at 7:28 -
In BASH, use this for seconds since last modified:
expr `date +%s` - `stat -c %Y /home/user/my_file`
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"
}
-
2Maybe that used to work under OS X, but now
-f%c
gives an error. Usingstat -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?– beroeCommented Oct 6, 2015 at 1:59 -
4At 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..– TimoCommented Jan 15, 2018 at 10:15