In Linux, file permissions dictate who can read, write, or execute a file or directory.
To view file permissions, use the ls -l command, which lists the contents of a directory along with their permissions. Each entry is preceded by a string representing the file type and permission settings.
-
The first character in the string represents the file type:
-: Regular filed: Directoryl: Symbolic linkc: Character device fileb: Block device files: Socketp: Named pipe (FIFO)
-
The next nine characters are grouped into three sets of three, representing permissions for the file owner, group, and others:
- The first set (positions 2-4) represents the owner's permissions.
- The second set (positions 5-7) represents the group's permissions.
- The third set (positions 8-10) represents others' permissions.
Each set can include:
r: Read permissionw: Write permissionx: Execute permission-: No permission
For example, in drw-r-xr-x:
d: This is a directory.rw-: The owner has read and write permissions.r-x: The group has read and execute permissions.r-x: Others have read and execute permissions.
Permissions can also be represented numerically using octal notation. Each permission set (owner, group, others) is represented by a number from 0 to 7, which corresponds to a combination of read (4), write (2), and execute (1) permissions:
| Number | Permissions | Binary |
|---|---|---|
| 0 | None | 000 |
| 1 | Execute | 001 |
| 2 | Write | 010 |
| 3 | Write and Execute | 011 |
| 4 | Read | 100 |
| 5 | Read and Execute | 101 |
| 6 | Read and Write | 110 |
| 7 | Read, Write, Execute | 111 |
For example, a permission of 755 means:
- Owner:
7(Read, Write, Execute) - Group:
5(Read, Execute) - Others:
5(Read, Execute)
The chmod command is used to change the permissions of files and directories. It can be used with symbolic or numeric (octal) notation.
Symbolic notation allows you to modify specific permission sets (user, group, others):
$ chmod u+rwx,g+rx,o-r myfile
This command grants the owner (u) read, write, and execute permissions, the group (g) read and execute permissions, and removes read permission from others (o).
$ chmod 755 myfile
This command sets the permissions to rwxr-xr-x, meaning the owner has full permissions, while the group and others have read and execute permissions.
You can change the ownership of a file or directory using the chown command:
$ sudo chown user:group filename
This command changes the ownership of filename to user and the group to group. Add -R to the command to change the ownership of all the contents of a directory.
- Setuid (s): Allows a file to be executed with the privileges of the file's owner. Set using
chmod u+s. - Setgid (g): Similar to setuid, but for the group. Set using
chmod g+s. - Sticky Bit (t): Ensures that only the file's owner, directory owner, or root can delete or modify a file. Set using
chmod +t.