如何获得时间,因为文件最后修改在几秒内与bash?

时间:2023-01-26 16:21:58

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

我需要以秒为单位获得上次修改文件后的时间。ls -l没有显示出来。

3 个解决方案

#1


59  

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

在Linux中,date -r文件打印文件最后一次修改的日期:

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:

要打印上次修改后的秒数,您可以使用expr,以秒为单位的当前日期减去最后一次修改的日期:

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.

在Mac OS X (BSD风格的日期)中,这是行不通的,你需要使用stat,就像其他的答案指出的那样。

#2


6  

I know the tag is Linux, but the stat -c syntax 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 "$1") )) "seconds ago"
}

#3


3  

In BASH, use this for seconds since last modified:

在BASH中,在上次修改后的几秒钟内使用:

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

#1


59  

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

在Linux中,date -r文件打印文件最后一次修改的日期:

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:

要打印上次修改后的秒数,您可以使用expr,以秒为单位的当前日期减去最后一次修改的日期:

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.

在Mac OS X (BSD风格的日期)中,这是行不通的,你需要使用stat,就像其他的答案指出的那样。

#2


6  

I know the tag is Linux, but the stat -c syntax 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 "$1") )) "seconds ago"
}

#3


3  

In BASH, use this for seconds since last modified:

在BASH中,在上次修改后的几秒钟内使用:

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