In Linux, the ability to modify file and directory permissions and ownership is crucial for maintaining security, privacy, and orderly access control. Permissions determine who can read, write, or execute a file, while ownership associates files with specific users and groups.
Changing File and Directory Permissions with chmod
The chmod (change mode) command is used to set or modify the read (r), write (w), and execute (x) permissions for user categories: owner (u), group (g), and others (o). Permissions can be changed either symbolically or numerically.
Symbolic Mode: Permissions are added (+), removed (-), or set (=) for specific user classes.
Syntax example:
chmod u+x filename # Adds execute permission to the owner
chmod g-w filename # Removes write permission from the group
chmod o=r filename # Sets others' permissions to read onlyUser classes:
Numeric (Octal) Mode: Permissions represented by numbers: read=4, write=2, execute=1
Add the values to set combined permissions:
7 (4+2+1) = read, write, execute
6 (4+2) = read, write
5 (4+1) = read, execute
Syntax example:
chmod 755 filename # rwx for owner, rx for group and others
chmod 644 filename # rw for owner, r for group and othersChanging Ownership with chown
Ownership associates files and directories with a user and group.
1. To change the owner:
chown username filename2. To change owner and group together:
chown username:groupname filename3. To change only the group:
chown :groupname filename4. To change ownership recursively (all files/directories inside a folder):
chown -R username:groupname directorynameNote: Changing ownership usually requires superuser (root) privileges, so prepend commands with sudo where necessary.
Changing Group Ownership with chgrp
The chgrp command specifically modifies the group owner of a file or directory:
chgrp groupname filenameIt is a simpler alternative to chown when only the group needs changing.
Practical Examples
1. Add execute permission for the user and group on a script:
chmod ug+x script.sh2. Change ownership of a file to user "john" and group "developers":
sudo chown john:developers project.txt3. Recursively change group ownership for all files inside /var/www to www-data:
sudo chgrp -R www-data /var/www4. Remove write permission for others on a file:
chmod o-w confidential.txtImportant Points
1. Only the file owner or root can modify permissions and ownership.
2. Incorrect permission settings can expose files to unauthorized access or prevent legitimate usage.
3. Recursive changes (chmod -R, chown -R) should be used carefully.
4. Use ls -l to verify permissions and ownership after changes.