chmod (Change Mode)
The chmod command is used to change the file mode bits (permissions) of a file or directory. It defines who can Read, Write, or Execute a specific file.
1. Permission Calculation (Numeric Mode)
Each permission is assigned a specific bit value. You determine the final permission by adding (OR-ing) these values:
- 4 (Read, r): Permission to read the file.
- 2 (Write, w): Permission to edit the file.
- 1 (Execute, x): Permission to run the file.
Combined into a 3-digit number (Owner / Group / Others): * 7 (4+2+1): Full permissions (rwx) * 6 (4+2): Read and Write (rw-) * 5 (4+1): Read and Execute (r-x)
2. Basic Usage
chmod [options] mode filename
3. Practical Examples
| Command | Description |
|---|---|
chmod 755 script.sh |
Owner: rwx, Group/Others: r-x (Standard for scripts) |
chmod 644 index.html |
Owner: rw-, Group/Others: r-- (Standard for web files) |
chmod 700 private.key |
Only the owner has access (rwx------) |
chmod -R 755 folder/ |
Recursive. Applies the mode to the directory and all contents. |
Symbolic Mode (Using Characters)
chmod u+s file: Add setuid bit for the user.chmod a+x file: Add execute permission for all users.chmod g-w file: Remove write permission from the group.
4. [Note] Connection to C Bitwise OR
In the Linux Kernel, permissions are handled using the bitwise OR operator ($|$).
$4 (100_2) \ | \ 2 (010_2) \ | \ 1 (001_2) = 7 (111_2)$
In C programming, you combine permission flags like this:
// Combining Read(4) and Write(2) constants
int my_mask = S_IRUSR | S_IWUSR; // Result is 6