1. Introduction
Chown is a Linux command that is used to change the owner of a list of directories or files. Chown has multiple options and we usually use it to change the group that owns the file or directory. Sometimes, we may need to change the owner of a directory with all files and folders that could be found within it. In this case, we use chown with recursion enabled. In this short tutorial, we'll show you how to recursively use the chown command to change folders and files owner.
2. Add folder ownership to a user recursively
To add ownership over a folder (or a list of folders) and all its contents to a specific user, you need to use the keyword chown with parameter -R that determines that chown is being used recursively.
$ chown -R <owner> <folder.1> <folder.2> ... <folder.n>
3. Add folder ownership to a user and group recursively
To add ownership over the folder and all its contents to a user and group, add user and group with semicolon separator after the -R parameter.
$ chown -R <user>:<group> <folder.1> <folder.2> ... <folder.n>
4. Add folder ownership to a user using find command
We can combine chown with the find command to find files matching a given pattern and changing their owners and groups.
$ find <path> -name <pattern> -exec chown <user>:<group> {} \;
An example of this would be:
$ find /home/documents -name *.txt -exec chown newUser {} \;
This command will find files matching *.txt pattern in /home/documents folder of the current user and execute chown on these files. In the end, newUser will be the owner of these files. If you want to be sure that your pattern is right, you can execute just the find command and see which files are eligible for change:
$ find /home/documents -name *.txt
5. Conclusion
In this tutorial, we demonstrated how to use chown to add folder ownership to users or groups recursively. Also, we showed how to use chown with find command.