Linux commands: chown

By

Published · Updated

Tagged: CLI

Learn how the Linux chown command changes the owner of a file or directory, sets owner and group at once, and applies changes recursively with the -R flag.

Every file/directory in an Operating System like Linux or macOS (and every UNIX systems in general) has an owner.

The owner of a file can do everything with it, including changing permissions with chmod.

Only root can change a file’s owner. You need sudo for that. The owner can only change the file’s group, and only to a group they belong to.

sudo chown <owner> <file>

Like this:

sudo chown flavio test.txt

For example if you have a file that’s owned by root, you can’t write to it as another user:

Terminal showing Permission denied error when trying to write to test.txt file as non-owner user

You can use sudo chown to transfer the ownership to you:

Terminal showing successful chown command transferring test.txt ownership to flavio user

It’s rather common to have the need to change the ownership of a directory, and recursively all the files contained, plus all the subdirectories and the files contained in them, too.

You can do so using the -R flag:

sudo chown -R <owner> <file>

Files/directories don’t just have an owner, they also have a group. Through this command you can change that simultaneously while you change the owner:

sudo chown <owner>:<group> <file>

Example:

sudo chown flavio:users test.txt

Leave the group empty and chown uses that user’s login group:

sudo chown flavio: test.txt

Be careful with -R. sudo chown -R flavio /var/www is a normal way to fix a web folder. sudo chown -R flavio / changes the owner of the whole disk and breaks the system.

You can also just change the group of a file using the chgrp command, to a group you’re a member of (or any group with sudo):

chgrp <group> <filename>

The chown command works on Linux, macOS, WSL, and anywhere you have a UNIX environment

Want me to talk about your product? You can sponsor this site.

Related posts about cli: