On Linux every file and directory has an owner, a group and a set of permission bits that decide who can do what. Understanding them solves a large share of "permission denied" errors, and prevents risky fixes.
Reading ls -l
-rwxr-x--- 1 alice developers 2048 Jan 15 10:00 deploy.shThe first character is the type (- file, d directory, l symbolic link). The next nine are three groups of three, for the owner, the group and others:
rread,wwrite,xexecute.rwxfor the owner,r-xfor the group and---for everyone else in this example.
Octal notation
Each permission has a value: read 4, write 2, execute 1. Add them for each of the three groups.
rwx= 7,r-x= 5,r--= 4,---= 0.- So
rwxr-x---is750.
chmod 750 deploy.sh # owner rwx, group r-x, others nothing
chmod u+x script.sh # add execute for the owner
chmod g-w shared.txt # remove write for the groupWhat the bits mean on directories
- r: list the names inside the directory.
- w: create, delete and rename entries inside (needs
xas well). - x: enter the directory and access items inside it by name.
A directory without x is unusable even if it is readable, a common source of confusion.
Owners and groups
chown alice:developers deploy.sh # change owner and group (needs privileges)
chgrp developers deploy.sh # change only the group
id # show your user and groupsNew files get permissions from the process's umask. With a umask of 022, files are created as 644 and directories as 755.
Good practice
- Follow least privilege: give the minimum required, and prefer groups over opening a file to everyone.
- Avoid
chmod 777. It lets any user modify the file and usually hides the real problem, which is the wrong owner or group. - Keep secrets such as private keys at
600and their directory at700. SSH refuses keys that are too open. - Run services as dedicated non-root users.
- Special bits such as setuid exist, but they are powerful. Use them rarely and review them.
Takeaway
Read the three triplets, think in octal, fix ownership before loosening permissions and keep secrets private.
Comments