Flash Sale:75% Off Hosting + Free DomainEnds in13h47m14sView Plans
Hostvento logoHostvento

Change Ownership of Files and Folders with chown -R

Give a new owner and group to a whole folder tree with one command, and avoid the common traps.

VPS and Cloud Servers2 min read3 steps7 screenshots

How ownership works

Every Linux file has an owner (user) and a group. They decide who can read, change or run it. See them with ls -l:

-rwxr-xr-- 1 karim devs file.txt
  • rwx are the rights of the owner (karim).
  • r-x are the rights of the group (devs).
  • r-- are the rights of everyone else.

Ownership works together with chmod, which sets the read, write and run rights.

File ownership shown by ls -l

Syntax

chown [options] new_user[:new_group] target

Add :group after the user to change the group too.

Recursive change with -R

-R makes chown walk through all folders and files below the target:

sudo chown -R karim:devs /srv/www
chown -R on a folder tree

Every item inside /srv/www now belongs to karim and the group devs.

By default, chown -R does not follow symbolic links. Two options change that:

sudo chown -RH karim /srv/www
sudo chown -RL karim /srv/www
chown with -RH and -RL

-H follows a link given on the command line. -L follows every link. Use them with care, because a link can lead outside the folder.

Safety first

  1. Back up before a big change:
rsync -a /var/www /backup/
Backing up with rsync
  1. Test the change with a dry run:
chown --dry-run -v -R karim:devs /path
chown dry run
  1. Large trees with many thousands of files can use a lot of disk I/O. Run them at a quiet time.

Examples

Change the owner only

sudo chown -R karim /opt/app
Owner changed for /opt/app

Change owner and group

sudo chown -R karim:devs /opt/app
Owner and group changed

Show only the files that change

chown -Rc karim .

Skip a folder, such as .git

find . -path './.git' -prune -o -exec chown karim:devs {} +

Using sudo

You need root rights to give files to someone else. If an admin should do it without a password, add a line like this with visudo:

karim ALL=(ALL) NOPASSWD: /bin/chown

Grant this only when it is needed.

Warning: Never run sudo chown -R root /. It can break the whole system. Always double-check the path.

Quick recap

  • chown -R user:group path changes a whole tree.
  • Back up and use --dry-run first.
  • Be careful with symbolic links and the path.