How to use chown recursively
What is chown?
chown is an abbreviation of ‘change ownership’ in unix and unix-like operating systems. Ownership is important in these operating systems because it gives users or groups certain permissions. You can check the ownership status of a file or directory by going into that directory and using the ls -l command. Try running the ls -l command in the terminal below:
Welcome to Educative!
Ignore all the other files and just consider the
filename.txtin this case.
-rwxrwxrwx 1 root root 21 Jul 6 06:38 filename.txt
// which corresponds to the following format
<PERMISSIONS> <USERNAME> <GROUPNAME> <SIZE> <MONTH> <DATE> <TIME> <FILENAME>
Now that you know what the ownership status is, you can use chown to change them. The basic syntax for chown is:
chown [OPTIONS] USER[:GROUP] FILE(s)
chownis often used with sudo or as a root because of the permissions necessary to use the command.
- You can set the
USERby writing the username followed by the filename. The syntax for a simple change owner command is:
chown <USERNAME> <FILENAME>
- Similarly, you can change the
GROUPby using the command:
chown :<GROUPNAME> <FILENAME>
You can also change the group by using the command
chgrp. The system call used is the same as that forchown.
- You can change both the user and group with:
chown <USERNAME>:<GROUPNAME> <FILENAME>
[OPTIONS]refers to the flags of the operation, which will affect how the operation is done. The one we will be looking at in this article is the-Ror--recursiveflag, which is used for recursive operations.
Write
man chownin your terminal or visit this page to see all the available flags.
How and why to use chown recursively
When working with directories, you need to use the -R flag. chown will work recursively on all subdirectories and files to make your specified changes:
chown -R <USERNAME>:<GROUPNAME> DIRECTORY
You can use -R with other flags like h:
chown -hR <USERNAME>:<GROUPNAME> DIRECTORY
Other options available in recursive mode are -L and -H. What these options do is listed below.
| Options | Description |
|---|---|
-h |
(also known as --no–dereference) Does not dereference symbolic link; instead, if the file is a symlink, it changes the file owner |
-L |
Traverses every symbolic link to encountered directories. |
H |
If a command-line argument is a symbolic link to a directory, traverse it. |
Free Resources