Understanding Linux File Permissions
File permissions are one of the cornerstones of Linux security. Every file and directory on a Linux system has an associated set of permissions that controls who can read, write, or execute it. Once you understand the model, managing access becomes intuitive and powerful.
The Three Permission Classes
Linux assigns permissions to three distinct classes of users:
- Owner (User): The user who created or owns the file.
- Group: A set of users who share access to the file.
- Others: Everyone else on the system.
Each class can be granted three types of access: read (r), write (w), and execute (x). When you run ls -l, you see something like:
-rwxr-xr-- 1 alice devs 4096 Jan 10 09:00 script.sh
Breaking this down: the first character (-) is the file type. The next nine characters are three groups of three — owner, group, and others permissions respectively.
Reading Permission Strings
| Symbol | Meaning |
|---|---|
r | Read — view file contents or list directory |
w | Write — modify file or add/remove files in directory |
x | Execute — run as a program or enter a directory |
- | Permission not granted |
Using chmod to Change Permissions
The chmod command changes file permissions. You can use it in two ways: symbolic mode and numeric (octal) mode.
Symbolic Mode
Symbolic mode uses letters to specify changes:
chmod u+x script.sh— add execute for the ownerchmod g-w file.txt— remove write from the groupchmod o=r file.txt— set others to read-onlychmod a+x script.sh— add execute for all classes
Numeric (Octal) Mode
Each permission has a numeric value: r=4, w=2, x=1. You add these together for each class:
chmod 755 script.sh— owner: rwx (7), group: r-x (5), others: r-x (5)chmod 644 file.txt— owner: rw- (6), group: r-- (4), others: r-- (4)chmod 600 private.key— owner: rw- (6), group: --- (0), others: --- (0)
Using chown to Change Ownership
The chown command changes the owner and/or group of a file. It requires root or sudo privileges:
sudo chown bob file.txt— change owner to bobsudo chown bob:developers file.txt— change owner to bob, group to developerssudo chown -R www-data:www-data /var/www/html— recursively change ownership
Common Permission Scenarios
- Web server files: Use
644for files and755for directories so the server can read but not modify them. - Shell scripts: Use
755or744to make scripts executable by the owner. - Private keys/configs: Use
600to restrict access to the owner only. - Shared directories: Use the sticky bit (
chmod +t /shared) so users can't delete each other's files.
Quick Tips
- Use
stat filenameto see full permission details including octal representation. - The
umaskcommand controls default permissions for newly created files. - Be careful with
chmod 777— it grants full access to everyone and is a security risk.
Understanding permissions is essential for keeping your Linux system secure. Practice regularly, and these concepts will become second nature.