How can I copy a file in Unix without altering its last modified time?

If I copy some file from some place to another using cp, the timestamp on the copied file is set to the time of the copy.

Is there some way to avoid this?

I need to copy files without altering their timestamps.


Solution 1:

cp -p does the trick. For Linux:

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

For FreeBSD:

-p Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, ACL, user ID, and group ID, as allowed by permissions.

And for OS X:

-p Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions. Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks, will also be preserved.

Note that this may/will change the source file's access time (atime), as shown by ls -lu. Also, stat or stat -x can be used to nicely show the data access, data modification, and file status change times, to which for macOS the birth time can be added using explicit formatting:

stat -f "%n%N%nAccess (atime): %Sa%nModify (mtime): %Sm%nChange (ctime): %Sc%nBirth  (Btime): %SB%n" *

Solution 2:

When using cp from the GNU Coreutils, to preserve only the timestamps and not attributes such as user id, group id or file mode there is the longhand --preserve which allows to explicitly specify a list of attributes to be preserved.

cp --preserve=timestamps source destination

Be aware though that this syntax is probably not supported on other Unices. An alternative could be to use the --times parameter of rsync which should be available on most installations.