Mastering File Permissions with chmod in Linux

What are File Permissions?

In Linux, each file and directory has three sets of permissions:

  • Read (r): Allows viewing the contents of a file or listing the files in a directory.
  • Write (w): Permits modifying the contents of a file or creating, deleting, and renaming files in a directory.
  • Execute (x): Enables running a program or script or entering a directory.

These permissions are assigned to three entities:

  1. Owner: The user who owns the file.
  2. Group: Users who belong to the same group as the file’s owner.
  3. Others: Users who are neither the owner nor in the group.

The chmod Command:

The chmod command allows users to change the permissions of a file or directory. Its syntax is as follows:

chmod [options] permissions file_or_directory

Numeric Representation:

The permissions are often represented numerically. Each permission has a numeric value:

  • Read (4)
  • Write (2)
  • Execute (1)

You can sum these values to represent a combination of permissions. For example, 7 means read (4) + write (2) + execute (1).

Examples:

1. Granting Read and Write to the Owner:

chmod u+rw file.txt

2. Revoking Execute Permission from Others:

chmod o-x script.sh

3. Setting Full Permissions for Owner and Read for Group and Others:

chmod 744 document.txt

Symbolic Representation:

Alternatively, chmod supports symbolic representation, providing a more explicit way to express permissions.

u (user), g (group), o (others):

Example: chmod u=rwx,g=r,o-rw file.txt grants the owner read, write, and execute permissions; the group has read permission, and others have no permissions.

Recursive Permission Changes:

To apply permissions recursively to all files and sub directories within a directory, use the -R option:

chmod -R 755 directory_name

In this example, the owner has read, write, and execute permissions, and the group and others have read and execute permissions for all files and sub directories within the specified directory.

Practical Usage:

Understanding and using chmod is crucial for tasks such as securing sensitive files, managing access control in shared environments, and ensuring the proper execution of scripts and programs.