0
0
Linux-cliHow-ToBeginner · 3 min read

How to Use chmod Command in Linux: Syntax and Examples

Use the chmod command in Linux to change file or directory permissions by specifying the permission mode and target file. The syntax is chmod [options] mode file, where mode can be symbolic (like u+r) or numeric (like 755).
📐

Syntax

The basic syntax of the chmod command is:

  • chmod: The command to change permissions.
  • [options]: Optional flags like -R for recursive changes.
  • mode: The permission settings, either symbolic (e.g., u+x) or numeric (e.g., 755).
  • file: The file or directory to change permissions on.
bash
chmod [options] mode file
💻

Example

This example shows how to give the owner execute permission on a file named script.sh using symbolic mode, and how to set full permissions for the owner and read-execute for group and others using numeric mode.

bash
touch script.sh
chmod u+x script.sh
ls -l script.sh
chmod 755 script.sh
ls -l script.sh
Output
-rw-r--r-- 1 user user 0 date script.sh -rwxr--r-- 1 user user 0 date script.sh -rwxr-xr-x 1 user user 0 date script.sh
⚠️

Common Pitfalls

Common mistakes include:

  • Using numeric mode without understanding what each digit means.
  • Forgetting to use -R when changing permissions recursively on directories.
  • Setting permissions too open (like 777) which can be a security risk.

Example of a wrong and right way:

bash
chmod 777 myfile.txt  # Too open, risky
chmod 755 myfile.txt  # Safer, common setting
📊

Quick Reference

PermissionSymbolicNumericDescription
Readr4Allows reading the file or listing directory contents
Writew2Allows modifying the file or directory contents
Executex1Allows running the file or entering the directory
Owneru-User who owns the file
Groupg-Users in the file's group
Otherso-Everyone else

Key Takeaways

Use chmod to change file permissions with symbolic or numeric modes.
Numeric mode uses three digits representing owner, group, and others permissions.
Use -R option to apply changes recursively to directories.
Avoid setting permissions to 777 to keep your system secure.
Check permissions with ls -l after changing them.