Structure
When ls -l ~/.bashrc prints -rw-r--r-- 1 student student 3771 ...,
it reads like this:
-is the object type (-file,ddirectory,lsymlink,c/bdevice)rw-are the owner's permissions (user)r--are the group's permissionsr--are the permissions for everyone else (other)
Each set is three flags:
| bit | meaning for a file | meaning for a directory |
|---|---|---|
| r | read the contents | list the files (ls) |
| w | change the contents | create/delete/rename files inside |
| x | run as a program | enter the directory (cd) and reach files by full path |
One detail: on a directory, r without x means "I see the names but
cannot enter and read individual files." It is rare, but it happens.
Octal notation
Each set is encoded as a single digit 0-7: r=4 + w=2 + x=1.
| mode | rwx | meaning |
|---|---|---|
| 7 | rwx | everything |
| 6 | rw- | read+write |
| 5 | r-x | read+execute |
| 4 | r-- | read only |
| 0 | --- | nothing |
A file's full permissions are three digits, for example 644 = rw-r--r--,
755 = rwxr-xr-x.
Commands
chmod 600 file.txt # rw------- (only the owner reads/writes)
chmod +x script.sh # add execute for everyone (u+g+o)
chmod u+x,g-w file # symbolic form: u/g/o + a (all)
chmod -R go-w /var/www # recursively remove write for group and other
chown: owner and group
chmod changes permissions. The owner is changed by chown:
sudo chown alice file.txt # change the owner
sudo chown alice:developers file.txt # owner + group
sudo chown -R www-data: /var/www # recursively
umask: permissions for new files
When a program creates a file (touch, > redirect), the real
permissions are desired_mode & ~umask. The default umask 022 means
new files are created without write for group and other, so
0666 & ~022 = 0644.
Special bits: setuid, setgid, sticky
Besides the usual rwx there are three extra bits (a 4th octal digit):
- setuid on an executable file: the program starts with the
effective UID of the file's owner, not of the user who runs it. This
is how
sudo,passwd, andpingwork - setgid on a directory: new files inside inherit the directory's group (useful for shared folders)
- sticky bit on a directory: only the owner of a file inside can
delete it, even if others have write on the directory. This is how
/tmpis protected
ls -ld /tmp /usr/bin/sudo
# drwxrwxrwt ... /tmp ← t = sticky
# -rwsr-xr-x ... /usr/bin/sudo ← s = setuid