Linux chmod Command
The chmod
command in Linux changes the permissions of files or directories, allowing you to control who can read, write, or execute them. This command is essential for managing access rights in a multi-user environment.
Permission Structure
Permissions in Linux are typically represented in three sets for:
- User (Owner)
- Group
- Others
Each set has three permissions:
- Read (
r
): View file content. - Write (
w
): Modify file content. - Execute (
x
): Run the file as a program or enter a directory.
Permissions are displayed as a string in the format rwxr-xr--
, where:
- The first character (
-
ord
) represents the type (file or directory). - The following sets of three characters represent permissions for the User, Group, and Others respectively.
Basic Syntax
Examples with Output
Example 1: Setting Permissions Using Symbolic Mode
Symbolic mode allows specifying permissions using symbols like +
, -
, and =
.
Command
Output
In this example:
chmod u+x file.txt
adds execute permission (x
) for the user (owner) only.- The
ls -l
command confirms thatfile.txt
is now executable by the user (rwx
for user).
Example 2: Removing Write Permission for Group
The following example removes write permission from the group.
Command
Output
Here, chmod g-w file.txt
removes the write permission (w
) from the group, so only the user has write access.
Example 3: Setting Permissions Using Numeric (Octal) Mode
Numeric mode uses numbers to represent each permission type:
- 4 for read (
r
) - 2 for write (
w
) - 1 for execute (
x
)
The three-digit number represents permissions for User, Group, and Others in that order.
Command
Output
Explanation:
7
=4+2+1
(read, write, execute) for User5
=4+1
(read, execute) for Group4
=4
(read) for Others
Example 4: Granting Read and Write Permissions to Everyone
To give read and write permissions to all users, you can use either symbolic or numeric mode.
Command
Output
Explanation:
chmod a+rw file.txt
grants read (r
) and write (w
) permissions to all (user, group, and others).- The
ls -l
output shows that everyone now has read and write access.
Example 5: Setting Special Permissions (SUID, SGID, and Sticky Bit)
- SUID (Set User ID): Allows a file to be executed with the permissions of the file owner.
- SGID (Set Group ID): Sets a directory so that new files inside inherit the directory’s group.
- Sticky Bit: Commonly used on directories, it restricts deletion of files to the file owner only.
Command: Setting SUID, SGID, and Sticky Bit
Output
Summary of Common Commands
chmod u+x file.txt
: Adds execute permission for the user.chmod 644 file.txt
: Sets read and write for the user, read-only for group and others.chmod a+rw file.txt
: Grants read and write permissions to everyone.
The chmod
command is a powerful tool for managing access rights in Linux, allowing you to control file and directory permissions securely.