Copy Files And Change The Ownership, Permissions At The Same Time
This brief tutorial describes how to copy files and change the ownership, permissions at the same time from command line in Unix-like operating systems. Usually, we use “cp” command to copy files from one location to another. Then, we use “chmod”, and “chown” commands to change the permissions and ownership of a file, respectively. However, we can combine all these tasks into a single one-liner command, and still get the same result instead of running the three consecutive commands. This can be helpful when you want to do this on a regular basis, or within a script.
Have a look at the following example.
To copy files and change permissions and ownership, we do:
However, you don’t have to use three commands to this simple task. We can do this with a single command. This is where the “install” command comes in help.
I thought “install” command is meant to install things. But, I am wrong! The “install” command is used to copy files into destination of your choice and set attributes. It is part of GNU coreutils, so it comes pre-installed with all Linux distributions.
Now, let me show how to change the permissions and ownership of a file during copy.
The above command will copy the file /dir1/file1 to /dir2, change the permissions of the file to 775, the owner to sk, and the group to ostechnix.
Let us break down the above command and see what each part of command does.
- -C, –compare : Compare each pair of source and destination files, and in some cases, do not modify the destination at all.
- -m, –mode : Set permission mode (as in chmod).
- -o, –owner : Set user ownership.
- -g, –group : Set group ownership.
For more details, refer man pages.