Bash – How to Get Modification Timestamp of a File Using Stat

bashfilesportabilitystattimestamps

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?

Best Answer

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