20

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.

Jake Berger
  • 5,237
  • 1
  • 28
  • 22
David Burson
  • 2,947
  • 7
  • 32
  • 55

2 Answers2

44

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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 3
    Finally a simple, straight to the point, no pompous and effective answer to this question! I can't believe how many people think that I actually care about learning all the 1,000 modifiers of stat or date commands...just gimme the command that works and that's it!! THANKS A LOT! – Clint Eastwood Sep 11 '15 at 23:37
2
# how-to list all the files and dir in a dir sorted by their
# modified time in the different shells 
# usually mac os / Unix / FreeBSD stat 
stat -f "%Sm %N" -t "%Y-%m-%d %H:%M:%S" ~/opt/comp/proj/*|sort 

# STDOUT output:
# 2018-03-27 15:41:13 ~/opt/comp/proj/foo
# 2018-03-28 14:04:11 ~/opt/comp/proj/bar

# GNU Utils ( usually on Linux ) stat 
# STDOUT output:
stat -c "%y %n" ~/opt/comp/proj/*|sort

# 2018-03-29 09:15:18.297435000 +0300 ~/opt/comp/proj/bar
# 2018-03-29 09:15:18.297435000 +0300 ~/opt/comp/proj/foo
Yordan Georgiev
  • 5,114
  • 1
  • 56
  • 53