What is chmod in Linux?

The chmod command in Linux is used to change the permissions of files and directories. The term "chmod" stands for "change mode," and it allows you to control who can read, write, or execute a file or directory.

Syntax:

chmod [options] mode file
  • mode: Specifies the permission changes, which can be in symbolic or numeric format.

  • file: Specifies the file or directory whose permissions you want to modify.

Types of Permissions:

  1. Read (r): Allows viewing the contents of a file or directory.

  2. Write (w): Allows modifying or deleting the contents of a file or directory.

  3. Execute (x): Allows running a file (e.g., a script) or accessing a directory.

Modes for Setting Permissions:

Permissions can be set using two main modes: symbolic mode and numeric mode.

Symbolic Mode:

In symbolic mode, the format is: [who][operator][permissions]

  • Who: Specifies the target (user, group, others, or all):

    • u: User (file owner)

    • g: Group

    • o: Others

    • a: All (user, group, others)

  • Operator: Specifies the action to take:

    • +: Add permissions

    • -: Remove permissions

    • =: Set exactly these permissions

  • Permissions: The permissions to set (read r, write w, execute x)

Examples:

  • Add execute permission for the user:

      chmod u+x file
    
  • Remove write permission for the group:

      chmod g-w file
    
  • Set read-only permission for everyone:

      chmod a=r file
    

Numeric Mode (Octal):

In numeric mode, each permission is represented by a number:

  • 4: Read (r)

  • 2: Write (w)

  • 1: Execute (x)

You combine these values to set permissions:

  • 7 = Read, Write, Execute (4 + 2 + 1)

  • 6 = Read, Write (4 + 2)

  • 5 = Read, Execute (4 + 1)

Example:

  • Set full permissions (read, write, execute) for the user, read-only for the group, and none for others:

      chmod 740 file
    

Conclusion:

The chmod command is essential for managing file and directory permissions in Linux, ensuring that only authorized users can access or modify sensitive files. It provides a flexible way to adjust permissions through symbolic or numeric modes, depending on your needs.