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

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

Posted by: admin November 29, 2017 Leave a comment

Questions:

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

Answers:

In Linux, date -r file prints the date when the file was last modified:

date +%s -r file.txt

To print the seconds elapsed since the last modification, you can use expr with the current date in seconds minus the date of the last modification:

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

In Mac OS X (BSD flavor of date) this won’t work, you’d need to use stat as other answers pointed out.

Questions:
Answers:

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"
}

Questions:
Answers:

In BASH, use this for seconds since last modified:

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