Linux:Copy, change permissions and ownership of a file in a command

8254

Today I came across a requirement to copy couple of files and change permissions to execute those files when writing some ansible playbooks. We can do this by using cp, chmodchowncommand as shown below. Ownership is changed from root user to normal user surendra.

ls -l abc.sh

output:

-rw-r–r– 1 root root 0 Jun 10 21:22 abc.sh

cp abc.sh /tmp/
chmod 755 /tmp/abc.sh
chown surendra.surendra /tmp/abc.sh

ls -l /tmp/abc.sh

Output:
-rwxr-xr-x 1 surendra surendra 0 Jun 10 21:23 /tmp/abc.sh

I can execute these commands with out any problem, but if you want to do same activity on a regular basis then it is time consuming task and more over keeping these commands in ansible play-book is not a great option. How about if we have a command in Linux which do all these stuff in one shot? Yes, we have a command called “install” which do this all in one command. The equivalent install command of above three commands is below.

install -v -g surendra -o surendra -m a+x abc.sh /tmp/abc.sh

To understand above command we should know couple of options for install command. Below examples will help you to understand install command with ease.

Example: Just copy a file from one location to other and do not bother about permissions and ownership.

install abc.sh /tmp

Example: Copy a file with different permissions, for example every user in my machine should have execute permission on the file

install -m a+x abc.sh /tmp/

Note: -m option arguments will be similar to chmod arguments.

Example: Copy a file with different permissions, for example full permissions for a file for all the users.

install -m 777 abc.sh /tmp/

Example: Copy a file with different owner name

install -m 755 -o surendra abc.sh /tmp/

Example: Copy a file with different group owner

read full post: http://www.linuxnix.com/linuxcopy-change-permissions-and-ownership-of-a-file-in-a-command/