Linux 如何获得自上次使用 bash 修改文件后的时间(以秒为单位)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19463334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-07 01:07:41  来源:igfitidea点击:

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

linuxbashunix

提问by mboronin

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

我需要获取自上次修改文件以来的时间(以秒为单位)。 ls -l不显示。

回答by Jason Enochs

In BASH, use this for seconds since last modified:

在 BASH 中,自上次修改以来使用它几秒钟:

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

回答by beroe

I know the tag is Linux, but the stat -csyntax doesn't work for me on OSX. This does work...

我知道标签是 Linux,但该stat -c语法在 OSX 上对我不起作用。这确实有效...

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 "") )) "seconds ago"
}

回答by janos

The GNU implementation of datehas an -roption to print the last modification date of a file instead of the current date. And we can use the format specifier %sto get the time in seconds, which is convenient to compute time differences.

的 GNU 实现date可以-r选择打印文件的最后修改日期而不是当前日期。并且我们可以使用格式说明符%s来获取以秒为单位的时间,这样可以方便地计算时差。

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 -rflag. To get the last modification seconds, you can use the statcommand instead, as other answers suggested. Once you have that, the rest of the procedure is the same to compute the elapsed seconds.

不幸的是date(例如在 Mac OS X 中)的 BSD 实现不支持该-r标志。要获得最后修改秒数,您可以改用该stat命令,如其他答案所建议的那样。完成后,其余过程与计算经过的秒数相同。