How To 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 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.
Copy Files And Change The Ownership, Permissions At The Same Time
Have a look at the following example.
To copy files and change permissions and ownership, we usually do:
$ cp /dir1/file1 /dir2
$ chmod 775 -R /dir2
$ chown -R newowner:newgroup /dir2/file1
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 handy.
I thought “install” command is meant to install things. But, I was wrong! The “install” command is used to copy files into destination of your choice and set attributes. It is part of GNU coreutils which comes pre-installed with all Linux distributions.
Now, let me show how to change the permissions and ownership of a file during copy.
$ sudo install -C -m 775 -o sk -g ostechnix /dir1/file1 /dir2
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.
$ man install
And, that’s all. Hope this helps.