3

I need to get the modification date of a file so that I can set it on other files using touch -m.

stat or perl -le 'print((stat shift)[9])' Didn't return what I wanted. I think that you are supposed to use - and + but I'm not sure how to use it correctly.

I though that using the -t I though it could set it another way, here I tried to set it to 2013 July the 3rd.

touch -t  20130703

But that didn't change it the way I want either. So back to the question, how do I copy another files attributes so that I can set them with touch -m?

  • Why? If you want to "copy another files attributes," why not use touch -r – John1024 Jan 21 '15 at 22:10
  • Yeah, I saw that but thats not what I want to do. I want to keep the string and maybe edit a folder and then change back the modification date etc. – DisplayName Jan 21 '15 at 22:16
4

You may convert the time returned by stat or perl to the format you want with the command date (assuming you have GNU coreutils installed):

# Convert UNIX time returned by perl to year+month+day
$ date -d @$(perl -le 'print((stat shift)[9])' FILENAME) +%Y%m%d
20130703

# Convert formatted time returned by GNU stat to year+month+day
$ date -d "$(stat -c %y FILENAME)" +%Y%m%d
20130703

date itself can give you the modification time for files directly too:

$ date -r FILENAME +%Y%m%d
20130703

For details, see the man page for GNU date (man date).

  • 1
    Note that stat -c is specific to GNU stat. Most other stat implementations (including OS/X which the OP mentions) can specify the date format. GNU find's -printf can also specify the date format. – Stéphane Chazelas Jan 21 '15 at 23:32
2
stat -f %m -t %Y%m%d%H%M.%S myfile

This prints the timestamp in the format required for touch -t.

Beware that the timestamp is expressed in the local timezone, which could be awkward to port files between timezones or for timestamps during the repeated hour of the summer-to-winter switch in timezones with DST. To avoid timezone trouble, use the UTC timestamp:

timestamp=$(TZ=UTC stat -f %m -t %Y%m%d%H%M.%S myfile)
…
TZ=UTC touch -t "$timestamp" myotherfile

Note that this applied to the BSD stat utility such as shipped with OSX, not to the GNU or BusyBox stat utilities such as found on Linux.

  • Note that to avoid issues around daylight saving switches, it's better to fix TZ to UTC0 for both touch and stat. – Stéphane Chazelas Jan 21 '15 at 23:42
-1

Doing "ls -otr --time-style=+%Y%m%d%H%M.%S" will get the date in the proper format, though with a bunch of other info that's easily edited out.

This is handy when assigned to an alias, and the output redirected to a file.

  • The OP tagged this OSX. --time-style is a feature of GNU coreutil's ls. – jordanm Jan 22 '15 at 3:33

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.