57

I need to a copy file and after that I need to change the timestamp attributes as the original file. How can I do it with the terminal or any other way?

4
  • 13
    Why "after that", specifically? you can preserve the timestamp (and other attributes) during copying by using the -p or --preserve= option e.g. cp -p oldfile newfile – steeldriver May 27 '18 at 13:23
  • 5
    @steeldriver Technically cp itself also does it afterwards. Please make cp --preserve=timestamps an answer – Sebastian Stark May 27 '18 at 13:30
  • This question must have been a duplicate when it was asked (the oldest (surviving) question is from early 2009) - more than 9 years in. Or in other words, how could such a basic question not have been asked already on this site during the first 9 years? – Peter Mortensen Feb 4 at 14:44
  • Corresponding question on Super User (2010): How can I copy a file in Unix without altering its last modified time? – Peter Mortensen Feb 4 at 14:46
27

If you want to preserve the original timestamps, use

$ touch -r <original_file> <new_file>

This copies the timestamps from another file.

See this blog post for more: Fake File Access, Modify and Change TimeStamps

106

You can preserve the timestamp of the original file when copying using cp by adding the -p or --preserve option:

   -p     same as --preserve=mode,ownership,timestamps

   --preserve[=ATTR_LIST]
          preserve the specified attributes (default: mode,ownership,time‐
          stamps), if  possible  additional  attributes:  context,  links,
          xattr, all

So to preserve only the timestamp

cp --preserve=timestamps oldfile newfile

or to preserve mode and ownership as well

cp --preserve oldfile newfile

or

cp -p oldfile newfile

Additional options are available for recursive copying - a common one is cp -a (cp --archive) which additionally preserves symbolic links.

3
  • 1
    Surprisingly, this did not work on macOS when copying from a FAT32 partition to an exFAT partition. – bonh May 7 '20 at 1:04
  • 5
    I think this should be the accepted answer. It solves the problem with one command which I think is what the OP was really after. It is also well explained. – FlexMcMurphy Aug 17 '20 at 23:33
  • 1
    Unfortunately timestamps aren't exactly the same. Eg source stat: Modify: 2020-08-31 14:32:41.481210326 -0600 after cp --preserve=timestamps target stat: Modify: 2020-08-31 14:32:41.000000000 -0600. You can see nanoseconds are different which is a bug in cp I guess. – WinEunuuchs2Unix Sep 19 '20 at 16:24

Your Answer

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