formatted modified date/time of file on mac bash?

David Burson picture David Burson · Aug 29, 2012 · Viewed 15.9k times · Source

In my bash script on mac (snow leopard) I have a path and filename, and I need to get the modified date/time of that file. I found I could do:
stat -f "%m" $MYFILE

However, that returns what I assume is epoch date/time. I need the date/time formatted: YYYYMMDDThhmmss. I've found all kinds of options (like date) that apparently depend on GNU, which on my mac I don't have.

What's the standard way to get a file's date/time modified in a user-specified format on mac (BSD?) bash. Or at least, a date/time formatting function that I can pass the result of my stat call above to.

Answer

chepner picture chepner · Aug 29, 2012

It's actually pretty simple, but different enough from GNU date that it's nowhere near obvious:

date -r $TIMESTAMP +%Y%m%dT%H%M%S

To get stat to do the formatting:

stat -f "%Sm" -t "%Y%m%dT%H%M%S" FILE