A few months ago I made a test of the behavior of cp
when the target file already exists:
$ ls -li
total 12
913966 -rw-rw-r-- 1 vagrant vagrant 30 Dec 16 20:26 file1
913965 -rwxrw---- 2 pete vagrant 39 Dec 16 20:35 file2
913965 -rwxrw---- 2 pete vagrant 39 Dec 16 20:35 hardlinktofile2
$ cat file1
This is the contents of file1
$ cat file2
This is the original contents of file2
$ cp file1 file2
$ ls -li
total 12
913966 -rw-rw-r-- 1 vagrant vagrant 30 Dec 16 20:26 file1
913965 -rwxrw---- 2 pete vagrant 30 Dec 16 20:37 file2
913965 -rwxrw---- 2 pete vagrant 30 Dec 16 20:37 hardlinktofile2
$ cat file1
This is the contents of file1
$ cat file2
This is the contents of file1
$
As you can see, the target file is overwritten in place and all its permissions, ownership, attributes, etc. are preserved—even hard links. The source file doesn't affect these in any way.
It wouldn't make any sense for mtime
to be preserved by default, and it isn't. But you'll notice that the new mtime
of file2
isn't taken from file1
—it's taken from the current system time.
You could do a similar test without having the target file in existence already, but this test actually illustrates the point more clearly: Only the actual content of the file is copied when no options are specified. File ownership, permissions, ACLs, mtime, et. al. are not set according to the source file, but instead are set in the same way they would be for a file newly created. (So, permissions according to umask
, mtime
according to the current time, ownership according to the EUID of the cp
process, etc.)
There is one specific but common exception:
In the absence of [the --preserve=] option, the permissions of existing destination files are unchanged. Each new file is created with the mode of the corresponding source file minus the set-user-ID, set-group-ID, and sticky bits as the create mode. (The operating system then applies either the umask or a default ACL, possibly resulting in a more restrictive file mode).
According to info coreutils 'cp invocation'
:
`xattr'
Preserve extended attributes if `cp' is built with xattr
support, and xattrs are supported and enabled on your file
system. If SELinux context and/or ACLs are implemented using
xattrs, they are preserved by this option as well.
This doesn't specify that extended attributes are preserved any other way than with this flag.
-p
flag. – Jeff Schaller Apr 11 '16 at 18:19