Linux File Permissions: chmod and chown

Every file and folder has an owner, a group, and permissions that control who can read it, change it and run it. chmod changes the permissions and chown changes the owner.

Reading permissions

ls -l script.sh
Shows the permissions at the start of the line, for example -rwxr-xr--. After the first character come three sets of three: the owner, the group, then everyone else. r means read, w means write and x means execute (run).

Changing permissions with letters

chmod +x script.sh
Makes a script executable so you can run it with ./script.sh.
chmod u+x,g-w,o-r notes.txt
Gives the owner (u) execute, removes write from the group (g) and removes read from others (o).

Changing permissions with numbers

Each set is a number made by adding read (4), write (2) and execute (1). So 7 is everything, 6 is read and write, 5 is read and execute, and 4 is read only.

chmod 644 notes.txt
Owner can read and write, everyone else can only read. Normal for documents and web pages.
chmod 755 script.sh
Owner can do everything, everyone else can read and run it. Normal for scripts and folders.
chmod 600 private.key
Only the owner can read and write. Use this for private keys and passwords.

Avoid chmod 777. It lets anyone on the system change or replace the file. There is almost always a safer way to fix a permissions problem.

Fixing a whole folder

chmod -R changes everything inside a folder, but it treats files and folders the same, which usually isn't what you want. These two commands set folders to 755 and files to 644:

find website -type d -exec chmod 755 {} +
Sets every folder inside website to 755.
find website -type f -exec chmod 644 {} +
Sets every file inside website to 644.

Changing the owner

Changing the owner of a file needs sudo.

sudo chown roger notes.txt
Makes the user roger the owner of notes.txt.
sudo chown roger:staff notes.txt
Sets both the owner and the group.
sudo chown -R www-data:www-data /var/www/html
Gives the web server user ownership of a website folder and everything in it.

Quick reference

OptionMeaning
4 / rRead
2 / wWrite
1 / xExecute (run), or open a folder
644rw-r--r--: documents and web pages
755rwxr-xr-x: scripts and folders
600rw-------: private files
u / g / oOwner / group / others