How to Use chmod to Change File Permissions in Linux
This article provides a comprehensive guide on using the
chmod (change mode) command to manage file and directory
permissions in the Linux operating system. You will learn the
fundamentals of the Linux permission model, how to read access rights,
and the step-by-step application of both numeric (octal) and symbolic
notations to secure or grant access to files.
Understanding Linux File Permissions
Every file and directory in Linux has an assigned set of permissions categorized by three user types:
- User (u): The owner of the file.
- Group (g): Members of the file's assigned group.
- Others (o): Everyone else on the system.
Each category can have three standard types of access:
- Read (r): Permission to view file contents or list directory files.
- Write (w): Permission to modify file contents or add/delete files in a directory.
- Execute (x): Permission to run a file as a script/program or enter a directory.
When running ls -l, permissions appear as a 10-character
string (e.g., -rwxr-xr--). The first character indicates
the file type (- for file, d for directory),
followed by three triplets representing permissions for User, Group, and
Others.
Method 1: Using Numeric (Octal) Mode
Numeric mode represents permissions using three-digit numbers. Each permission type has an assigned numeric value:
- r (read): 4
- w (write): 2
- x (execute): 1
- - (no permission): 0
Add the values together to generate a single digit for each user category:
- 7 (4+2+1): Read, write, and execute
- 6 (4+2): Read and write
- 5 (4+1): Read and execute
- 4 (4): Read-only
- 0: No permissions
Syntax:
chmod [numeric_code] [filename]Common Examples:
- Standard file permissions (Read and write for owner;
read-only for others):
chmod 644 file.txt - Executable script (Full rights for owner; read and execute
for others):
chmod 755 script.sh - Private file (Full access only for owner; no access for
anyone else):
chmod 700 private.key
Method 2: Using Symbolic Mode
Symbolic mode uses characters and mathematical operators to modify specific permissions without needing to calculate numeric values.
Operators:
+: Adds a permission.-: Removes a permission.=: Sets exact permissions, overwriting existing ones.
Syntax:
chmod [who][operator][permission] [filename]Common Examples:
- Make a script executable for the owner only:
chmod u+x script.sh - Remove write permission for both group and others:
chmod go-w document.txt - Grant read and write permissions to everyone:
chmod a+rw shared.txt - Set exact permissions (read and write for owner, read-only
for group):
chmod u=rw,g=r,o= file.txt
Applying Permissions Recursively
To apply permission changes to a directory and all files and
subdirectories within it, use the -R (recursive) flag:
chmod -R 755 /path/to/directoryNote: Be cautious when running recursive chmod
commands, especially with root privileges, as incorrectly altering
system file permissions can cause system instability.