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.shShows 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.shMakes a script executable so you can run it with ./script.sh.
chmod u+x,g-w,o-r notes.txtGives 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.txtOwner can read and write, everyone else can only read. Normal for documents and web pages.
chmod 755 script.shOwner can do everything, everyone else can read and run it. Normal for scripts and folders.
chmod 600 private.keyOnly 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.txtMakes the user roger the owner of notes.txt.
sudo chown roger:staff notes.txtSets both the owner and the group.
sudo chown -R www-data:www-data /var/www/htmlGives the web server user ownership of a website folder and everything in it.
Quick reference
| Option | Meaning |
|---|---|
4 / r | Read |
2 / w | Write |
1 / x | Execute (run), or open a folder |
644 | rw-r--r--: documents and web pages |
755 | rwxr-xr-x: scripts and folders |
600 | rw-------: private files |
u / g / o | Owner / group / others |