If you need to brush up on file ownership and permissions please read this article first.
In this tutorial we will cover how to change user and group ownership of files and directories. To find out who owns a file or what group it belongs to there are two main options.
ls -l and
ls -l will give a long listing of the files, including the owner and group of a file.
stat will give you quite a bit of information about a specific file.
ls -l is the one to use generally.
When you run the ls -l command you will get an output similar to this:
[email@example.com pairtest]# ls -l total 0 -rw-r--r--. 1 root root 0 Sep 5 19:04 named.conf -rw-r--r--. 1 root root 0 Sep 5 19:04 notes.txt drwxr-xr-x. 2 root root 4096 Sep 5 19:10 test
There are two files here. As you can see they are owned by root and belong to the group called root. In the following sections and examples we will use the above two files to demonstrate what we are doing.
Changing file ownership with
The chown command has the following format
chown [user] filename [options].
In the above example I created two files as root user in the ~pairtest directory. I now want that the user “pairtest” to be able to have full control over those files. To do this we use
chown pairtest named.conf. If we want to change all files in that folder at the same time we can use the wildcard for the filename argument:
chown pairtest *
-rw-r--r--. 1 pairtest root 0 Sep 5 19:04 named.conf -rw-r--r--. 1 pairtest root 0 Sep 5 19:04 notes.txt drwxr-xr-x. 2 pairtest root 4096 Sep 5 19:10 test
As you can see they are now owned by the user pairtest. However if we do
ls -l test we can see the files inside the directory “test” are still owned by root.
-rw-r--r--. 1 root root 0 Sep 5 19:12 test.txt
To change all files and directories we need to use the -R recursive option. So to change everything in this directory and everything in each subdirectory we would use
chown pairtest * -R
Changing group ownership using
The chgrp command has the following format
chgrp [group] filename [options].
chgrp does exactly the same as chown but for the group ownership of a file or directory.
So to change the group ownership of all files and directories recursively we would use
chgrp pairtest * -R
Changing both group and owner
If you just want to change either the owner or the group then it is recommended that you use the relevant command as outlined above. However if you want to alter both you can use the chown command to do both. To do this use the command
chown username.groupname filename. To replicate the above two commands in a single command use
chown pairtest.pairtest * -R
Changing the owner or group using a reference file
If you want to change a lot of files and directories so their owner and group matches another file then you can use the
--reference option. To change all files and directories recursively so they match the same as
/root/testfile.txt you would use
chown --reference=/root/testfile.txt * -R