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

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" *

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.


There are three times on a Unix filesystem, the access time (atime), the modification time (mtime), and the inode change time (ctime). You can change the access time and the modification time with the touch program, for example

cp orig copy
touch -r orig copy

However, you cannot change the inode change time.

Tags:

Unix

Timestamp