17

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?

3 Answers 3

24

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
1
  • Other BSD won't show as Darwin. It might be better to check the version of stat itself. stat --version |& grep -q GNU will be true on GNU and false on BSD (--version will actually return an error there)
    – mwfearnley
    Commented Apr 18, 2023 at 14:38
8

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
8

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

Output of stat on OSX

2
  • 1
    i think you are missing -x option on OSX.
    – del bao
    Commented Mar 6, 2017 at 22:48
  • @Derry you are correct, sadly I have to rely on research for the OSX bits as I don't have OSX. Corrected answer.
    – Elder Geek
    Commented Mar 6, 2017 at 22:59

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .