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?


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


   %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"
    mod_time_fmt="-c %Y"

And then use this value in the stat command wherever needed:

stat $mod_time_fmt .bashrc

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

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-



Output of stat on OSX

  • 1
    i think you are missing -x option on OSX. – fushupinnanren Mar 6 '17 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 Mar 6 '17 at 22:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.