How to change owner of folder to current user recursively?

Using sudo nautilus I created some folders and I want to get rid of root permission on them. But I have many and I want to do it to a entire directory and its containing folders.

So how to allow read/write to current user to all files and folders inside a specific directory that is inside /home?


To revert damage done using sudo nautilus you should make yourself the owner of any directories (and their contents) that are owned by root.

You can use find to do this, as it has a test to find only files owned by a specific user.

This will find all the directories in your home owned by root:

sudo find ~ -type d -user root

You can then repeat the find command and add the action you want to do - recursively changing ownership of all the found directories and their contents to the current user:

sudo find ~ -type d -user root -exec sudo chown -R $USER: {} +

Explanation:

  • ~ the home directory
  • -type d find only directories
  • -user root find only stuff belonging to root
  • -exec do the following command on whatever was found
  • sudo chown -R recursively change owner
  • $USER the current user
  • : also change group to the specific user

More efficiently, you could omit the -type d to find files of any type belonging to root, and also omit the -R as find will do the recursion for you by acting on all the files

sudo find ~ -user root -exec sudo chown $USER: {} +

Running GUI tools, like nautilus as root is Considered Harmful for this reason, among others (hidden functions, ability to silently run program fragments from who knows where, ...).

You don't have a "permission" problem, you have an "ownership" problem.

To find all the files owned by root (really owned by anybody else), do:

sudo find $HOME \! -user $USER

To change the ownership back to you, you could

sudo chown -R $(id -u):$(id -g) $HOME

but that will change the ownership of all files in and under $HOME

sudo find $HOME \! -user $USER >/tmp/list-of-files
# edit the list of files, and delete file files you don't want to chown
nano /tmp/list-of-files 
xargs sudo chown $(id -u):$(id -g) </tmp/list-of-files

Gives one the opportunity to adjust the list of files, owned by not-you, that will have their ownership changed back to you.


What you need to do is change the ownership of the folder from the user (and group) root to the other user (and group) you want.

Imagine you want to work on /home/randomFolder, and that the user you want to handle ownership to is vitor-abella, what you need to do is simply execute this as root:

chown -R vitor-abella:vitor-abella /home/randomFolder

It may take a while if there's a lot of files and subfolders, but after that you should be on track.

Cheers.