How To Copy Files And Change The Ownership, Permissions At The Same Time

One-liner Linux Commands

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.

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 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 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.

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

Recommended Read: ExplainShell – Find What Each Part Of A Linux Command does

And, that’s all. You know now how to copy files and change their ownership, permissions at the same time. If you find this guide useful, please share it on your social, professional networks and support OSTechNix. More good stuffs to come. Stay tuned.


Thanks for stopping by!

Help us to help you:

Have a Good day!!

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.