stat: modification timestamp of a file
Solution 1
Ubuntu uses the GNU coreutils stat
, whereas OSX uses the BSD variant. So on Ubuntu the command is a bit different:
stat -c %Y .bashrc
From man stat
:
-c --format=FORMAT use the specified FORMAT instead of the default; output a new‐ line after each use of FORMAT
and:
%Y time of last data modification, seconds since Epoch
If you want a portable way to run these regardless of OS, then there are several ways of doing it. I think I would set a variable one time to the appropriate parameters:
if uname | grep -q "Darwin"; then
mod_time_fmt="-f %m"
else
mod_time_fmt="-c %Y"
fi
And then use this value in the stat
command wherever needed:
stat $mod_time_fmt .bashrc
Solution 2
since the OSX and Ubuntu versions of stat
have some differences in that OSX stat
defaults to terse output and Linux stat
defaults to verbose some hoops would need to be jumped through. One possibility would be to simply use an alias on OSX would make stat perform the same on both.
If you don't mind setting an alias to force verbose output of stat
on OSX with alias stat="stat -x"
then you don't need perl.
stat .bashrc| grep Modify
is all you need under Ubuntu. if you set the alias as above it works under OSX as well
Example from Ubuntu 14.04.5 Virtually identical results can be obtained from Ubuntu 16.04
stat .bashrc| grep Modify
Modify: 2014-03-30 23:14:47.658210121 -0500
If all you want is the timestamp you can strip the Modify:
and retain the rest with
stat .bashrc| grep Modify | cut -c 9-
Sources:
https://ss64.com/osx/stat.html
Solution 3
It depends on what you mean by "this". If you're asking whether there is a portable way to get a file's mtime
with stat(1)
, then no, there isn't. BSD stat(1)
is different from Linux stat(1)
.
If you're asking whether there is a portable way to get a file's mtime
, then yes, you can do that with perl(1)
:
perl -e 'print +(stat $ARGV[0])[9], "\n"' file
Related videos on Youtube
del bao
Updated on September 18, 2022Comments
-
del bao over 1 year
I use
stat -f %m .bashrc
to get modification time of my .bashrc on osx. But when I run the same command on ubuntu, it spits error:stat: cannot read file system information for %m': No such file or directory
is there a compatible way to achieve this?
-
del bao about 7 yearsi think you are missing -x option on OSX.
-
Elder Geek about 7 years@Derry you are correct, sadly I have to rely on research for the OSX bits as I don't have OSX. Corrected answer.