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 /etc/shells is owned by root, so you can’t write to it as your regular user:

Terminal showing ls -l /etc/shells owned by root and wheel, then echo test >> /etc/shells failing with Permission denied

When it’s a file of yours that ended up owned by root, like a test.txt created with sudo touch, you can use sudo chown to transfer the ownership to you:

Terminal showing sudo touch test.txt, a Permission denied when writing to it, then sudo chown flaviocopes test.txt and a write that works

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: