Reading the three digits
A chmod mode has three digits for the owner, the group and everyone else, in that order. Each digit adds up three values: read is 4, write is 2 and execute is 1. So 7 is 4+2+1, all three, and 5 is 4+1, read and execute.
The modes you'll see most:
- 755, rwxr-xr-x: the owner can do anything, everyone else can read and run. Programs and directories.
- 644, rw-r--r--: the owner can edit, everyone else can read. Ordinary files.
- 600, rw-------: the owner only. Private keys and secrets.
- 700, rwx------: the owner only, with execute. Private directories.
- 777, rwxrwxrwx: anyone can change it. Avoid it.
Files and directories read the bits differently
On a file, execute means you can run it. A script without the bit gives "Permission denied" when you run ./script.sh, which is why chmod +x is the first fix. On a directory, read lets you list the names inside, execute lets you reach the items by name, and write lets you create, rename and delete entries. Write without execute does nothing useful. That's why directories usually get 755 and files 644.
It also makes recursive changes easy to get wrong. chmod -R 644 project/ strips execute from every folder and locks you out of it. Use a capital X instead: chmod -R u=rwX,go=rX project/ adds execute only to directories and to files that already had it for someone.
Symbolic mode and chmod +x
Symbolic mode edits bits instead of replacing the whole mode. chmod u+x file adds execute for the owner, chmod go-w file removes write from group and others, and chmod a=r file makes it read only for everyone. A 644 file becomes 744 after chmod u+x and 654 after chmod g+x.
A plain chmod +x with no letter is the odd one. It applies to everyone, except for bits set in your umask. At the common umask 022 it turns 644 into 755. At 077 it gives 744, since group and others are masked out. Name the letter, like u+x or a+x, when the result has to be exact. The chmod +x page works through the rule.
The extra digit, and modes to avoid
A fourth digit in front sets the special bits: setuid is 4, setgid is 2 and sticky is 1. On a directory, setgid makes new files inherit the directory's group, and sticky stops users from deleting files they don't own. Most daily work never needs them.
The mode to avoid is 777. It lets every user on the machine change the file or run it, and it usually hides a problem that an owner or group change would fix properly. The chmod 777 page lists safer options. For secrets, go the other way: 600, or 400 if nothing should write to the file, as in private key permissions. New files never start at 777 anyway. They get trimmed as they're created.