Preserve the timestamp, ownership and permissions of a file
When you copy a file on Linux, information about certain attributes is not copied along. For instance, the timestamps, ownership and mode (or file permissions) from the original file will be lost.
Instead, the current timestamp will be used as the timestamp, the current user (and group) will take ownership of the file and the file permissions will be the default permissions. (The same applies to directories by the way.)
If you need to preserve the original mode, timestamps or ownership, you can specify an option to the cp
command: --preserve=[ATTR_LIST]
.
From the man
page:
--preserve[=ATTR_LIST]
preserve the specified attributes (default: mode,ownership,time‐
stamps), if possible additional attributes: context, links,
xattr, all
Examples
Default
After we copy original.txt
to copy.txt
using no preserve options the attributes will look something like this:
$ cp original.txt copy.txt
$ ls -l
-rw-r--r-- 1 marek staff 9 Jan 7 22:30 copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 original.txt
As you can see, the timestamps, ownership and permissions are different. The owner of the original file was _www
, now it is the current user, which is marek
. The original timestamp on the original was 22:27
, the copy has 22:30
. And the (quite remarkable) permissions -rwxrw-r-x
are now the default -rw-r--r--
(or 644) permissions.
Timestamps
To retain the original timestamps we only need to specify it like this:
$ cp --preserve=timestamps original.txt copy.txt
Which results in the same timestamps:
-rw-r--r-- 1 marek staff 9 Jan 7 22:27 copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 original.txt
Ownership
To retain the ownership the command is similar:
$ cp --preserve=ownership original.txt copy.txt
Now, we have:
-rw-r--r-- 1 _www staff 9 Jan 7 22:34 copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 original.txt
Mode / Permissions
As you probably have guessed, to keep the file permissions:
$ cp --preserve=mode original.txt copy.txt
And now both files have the permissions -rwxrw-r-x
:
-rwxrw-r-x 1 marek staff 9 Jan 7 22:37 copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 original.txt
All together
Note that we can combine all these commands to preserve the timestamps, ownership and permissions:
$ cp --preserve=timestamps,ownership,mode original.txt copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 copy.txt
-rwxrw-r-x 1 _www staff 9 Jan 7 22:27 original.txt
If you followed along closely, you might have noticed in the man
page a shorthand option -p
to preserve the mode, ownership and timestamps at the same time:
-p same as --preserve=mode,ownership,timestamps
So, instead of the command above, you could also do this:
$ cp -r original.txt copy.txt