112

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?

2
  • 17
    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 May 27, 2018 at 13:23
  • 7
    @steeldriver Technically cp itself also does it afterwards. Please make cp --preserve=timestamps an answer May 27, 2018 at 13:30

3 Answers 3

174

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
  • 3
    Surprisingly, this did not work on macOS when copying from a FAT32 partition to an exFAT partition.
    – bonh
    May 7, 2020 at 1:04
  • 6
    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. Aug 17, 2020 at 23:33
  • On a Mac, use gcp (GNU cp from coreutils, as in brew install coreutils)
    – peak
    Jan 1 at 8:55
50

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

2
  • Will this work for folders, or all files in a folder?
    – aqk
    Apr 2, 2022 at 20:48
  • 4
    Helpful when you left -p option out of a cp, thanks.
    – Andrew
    Oct 25, 2022 at 18:37
2

If for instance you forgot the cp -p parameter and need to replace timestamps with their originals recursively without recopying all the files. Here is what worked for me:

find /Destination -exec bash -c 'touch -r "${0/Destination/Source}" "$0"' {} \;

This assumes a duplicate file/ folder tree of Source: /Source and Destination: /Destination

  1. find searches the Destination for all files & dirs (which need timestamps) and -exec ... {} runs a command for each result.
  2. bash -c ' ... ' executes a shell command using bash.
  3. $0 holds the find result.
  4. touch -r {timestamped_file} {file_to_stamp} uses a bash replace command ${string/search/replace} to set timestamp source appropriately.
  5. the Source and Destination directories are quoted to handle dirs with spaces.

You must log in to answer this question.