stat:文件的修改时间戳

fus*_*ren 14 bash stat timestamps files portability

我用来stat -f %m .bashrc在 osx 上获取我的 .bashrc 的修改时间。但是当我在 ubuntu 上运行相同的命令时,它吐出错误:

stat: cannot read file system information for %m': No such file or directory

有没有兼容的方法来实现这一目标?

Dig*_*uma 16

Ubuntu 使用 GNU coreutils stat,而 OSX 使用 BSD 变体。所以在 Ubuntu 上,命令有点不同:

stat -c %Y .bashrc
Run Code Online (Sandbox Code Playgroud)

来自man stat

   -c  --format=FORMAT
          use the specified FORMAT instead of the default; output  a  new?
          line after each use of FORMAT
Run Code Online (Sandbox Code Playgroud)

和:

   %Y     time of last data modification, seconds since Epoch
Run Code Online (Sandbox Code Playgroud)

如果您想要一种可移植的方式来运行这些而不考虑操作系统,那么有几种方法可以做到。我想我会一次性为适当的参数设置一个变量:

if uname | grep -q "Darwin"; then
    mod_time_fmt="-f %m"
else
    mod_time_fmt="-c %Y"
fi
Run Code Online (Sandbox Code Playgroud)

然后在stat命令中需要的地方使用此值:

stat $mod_time_fmt .bashrc
Run Code Online (Sandbox Code Playgroud)


Sat*_*ura 8

这取决于你所说的“这个”是什么意思。如果你问是否有一个可移植的方式来获得文件的mtime使用stat(1),则没有,没有。BSDstat(1)不同于 Linux stat(1)

如果您问是否有一种可移植的方式来获取文件的mtime,那么是的,您可以使用perl(1)

perl -e 'print +(stat $ARGV[0])[9], "\n"' file
Run Code Online (Sandbox Code Playgroud)


Eld*_*eek 8

因为 OSX 和 Ubuntu 版本stat有一些差异,OSXstat默认为简洁输出,Linuxstat默认为冗长,需要跳过一些箍。一种可能性是在 OSX 上简单地使用别名会使 stat 在两者上执行相同的操作。

如果您不介意设置别名来强制statOSX 上的详细输出,alias stat="stat -x"那么您不需要 perl。

stat .bashrc| grep Modify 这就是你在 Ubuntu 下所需要的。如果你像上面一样设置别名,它也可以在OSX下运行

来自 Ubuntu 14.04.5 的示例 可以从 Ubuntu 16.04 获得几乎相同的结果

   stat .bashrc| grep Modify
Modify: 2014-03-30 23:14:47.658210121 -0500
Run Code Online (Sandbox Code Playgroud)

如果你想要的只是时间戳,你可以剥离Modify:并保留其余的

stat .bashrc| grep Modify | cut -c 9-

资料来源:

https://ss64.com/osx/stat.html

OSX 上的 stat 输出