In this tutorial, we will look at copying files in Linux using the cp command and preserving the existing permissions and ownership on the files which are being copied. By default, the cp command will change the owner of the destination files to the person who did the copy. It will also change the permissions on these files to default permissions; usually 644.
Note that the user who is performing the copy must have at least the same permissions on the source files when attempting to preserve these permissions at the destination. By performing the copy as root (the superuser), you can be sure that permissions and ownership will be properly preserved.
We use the -p flag to tell cp to preserve the permissions and ownership of the files involved. So if we wanted to copy a folder recursively preserving permissions and ownership of the folder and the files contained in it, we would use the following command (preferably as root):
cp -R -p /source/folder/ /destination/folder/
All the files in the source folder would be copied to the destination folder and the permissions and owners would be preserved.
If we had a single file it would be similar:
cp -p /path/to/file-a /path/to/file-b
To check that the owner and permissions have been preserved, we can simply use:
ls -altp /destination/folder/
The result of the above command would show us the permissions that the files in the destination folder have.
Assuming you are logged in as root and you have a user called vince on the system, if you ran the following commands:
touch a cp a b chown vince b chmod 777 b cp -p b c cp b d ls -altp
You would get:
So we can see that c has the same permissions and owner as b, but d has a different owner and permissions since we did not tell cp to preserve those attributes in the destination file.
We hope this tutorial was helpful.