简体   繁体   中英

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

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

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.

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

在BASH中,自上次修改后使用此秒数:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM