The nine permission bits
◈ 9 cardsConverting between rwxr-x--x, 751 and the nine underlying bits in both directions, cold and without a calculator.
Nine bits, three at a time
Three permissions — read, write, execute — times three classes — owner, group, other — is nine bits, and nine bits is the whole basic scheme. They live in the file's inode alongside the owner UID and the group GID, and ls -l prints them as the nine characters after the file-type character:
-rwxr-x--x 1 ada dev 4096 Sep 1 10:12 build.sh
^~~~~~~~~~
| owner group other
file type
A bit that is set prints as r, w or x according to its position; a bit that is clear prints as -. Position is everything: the second character of a triple is always the write bit, so -w- and rw- differ in one bit even though they look nothing alike.
One octal digit per triple
Three bits is exactly one octal digit, and that is why UNIX permissions are quoted in octal rather than in decimal or hex. Within a triple the weights are r = 4, w = 2, x = 1, and the digit is their sum:
| bits | digit | meaning |
|---|---|---|
--- | 0 | nothing |
--x | 1 | execute / search only |
-w- | 2 | write only |
-wx | 3 | write and execute |
r-- | 4 | read only |
r-x | 5 | read and execute |
rw- | 6 | read and write |
rwx | 7 | everything |
Three digits, owner then group then other, left to right — so the whole range is 000 to 777.
Worked example — both directions, digit by digit
Symbolic to octal. Take rwxr-x--x and cut it into threes:
rwx r-x --x
111 101 001
7 5 1
rwx is 4 + 2 + 1 = 7. r-x is 4 + 0 + 1 = 5. --x is 0 + 0 + 1 = 1. The mode is 751.
Octal to symbolic. Now reverse 640. Take one digit at a time and split it into 4, 2 and 1:
6 4 0
110 100 000
rw- r-- ---
6 is 4 + 2, so read and write, no execute: rw-. 4 is read alone: r--. 0 is nothing: ---. The mode is rw-r----- — a file the owner can edit, the group can read, and nobody else can even open.
The one habit worth building
Do not memorise a table of nine modes. Memorise 4, 2, 1 and split every digit on sight. That habit converts in either direction at the same speed, it does not break on an unfamiliar mode like 716, and it is the same arithmetic you will need again for umask and for the leading special-bit digit.