The chmod
(short for “change mode”) command is used to change the permissions of files and directories in Linux. This command allows you to control who can read, write, or execute a file or directory. Permissions are set using either symbolic or numeric modes.
Initial Example
To make a script file executable by the owner, you would use:
chmod u+x script.sh
Understanding File Permissions
In Linux, each file and directory has three types of permissions for three different categories of users:
- Owner (u): The user who owns the file.
- Group (g): The group that owns the file.
- Others (o): All other users.
Permissions are represented by three letters:
- r: Read permission.
- w: Write permission.
- x: Execute permission.
CHMOD Parameters
Parameter | Description |
---|---|
-c, --changes | Report only when a change is made, similar to verbose but more selective. |
-f, --silent, --quiet | Suppress most error messages. |
-v, --verbose | Output a diagnostic for every file processed. |
--dereference | Apply changes to the referent of each symbolic link, rather than the symbolic link itself. |
-h, --no-dereference | Affect each symbolic link itself, rather than the referent. |
--no-preserve-root | Do not treat ‘/’ specially (this is the default behavior). |
--preserve-root | Fail to operate recursively on ‘/’. |
--reference=RFILE | Use RFILE’s mode instead of specifying MODE values. RFILE is always dereferenced if a symbolic link. |
-R, --recursive | Change files and directories recursively. |
-H | Traverse the directory if a command-line argument is a symbolic link to it. |
-L | Traverse every symbolic link to a directory encountered. |
-P | Do not traverse any symbolic links. |
--help | Display help text and exit. |
--version | Output version information and exit. |
Examples
1. Using Symbolic Mode
To change permissions using symbolic mode, you specify who the permissions apply to and what you want to change:
- Adding Permissions: Use
+
to add a permission.
chmod u+r filename.txt
- Removing Permissions: Use
-
to remove a permission.
chmod g-w filename.txt
- Setting Specific Permissions: Use
=
to set specific permissions.
chmod o=x filename.txt
2. Using Numeric Mode
Permissions can also be set using a three-digit octal (base-8) value. Each digit represents a different category of users:
- Read (r): 4
- Write (w): 2
- Execute (x): 1
For example, to set read, write, and execute permissions for the owner, and read and execute permissions for the group and others:
chmod 755 filename.txt
Here’s the breakdown:
- Owner: 7 (4+2+1 = rwx)
- Group: 5 (4+1 = r-x)
- Others: 5 (4+1 = r-x)
3. Changing Directory Permissions
To change permissions for a directory and all its contents, use the -R
(recursive) option:
chmod -R 755 /path/to/directory