/

Understanding the Linux Command: chmod

Understanding the Linux Command: chmod

tags: [“Linux”, “macOS”, “UNIX”, “file mode”, “permissions”, “chmod command”]

In the Linux, macOS, and UNIX operating systems, every file has three permissions: read, write, and execute. These permissions are represented by a string of characters when using the ls -al command. Understanding and changing file permissions is important for managing access to files and directories.

Let’s dissect the permission string: drwxr-xr-x.

The first character represents the type of file:

  • - indicates a normal file
  • d indicates a directory
  • l indicates a link

The next three sets of characters represent the permissions for the owner, group, and everyone else, respectively. Each set consists of three values: read (r), write (w), and execute (x). If a permission is not granted, it is represented by a -.

To change the permissions of a file, we use the chmod command. There are two ways to use it: symbolic arguments and numeric arguments.

Symbolic arguments are more intuitive. You start with chmod, followed by a space and a letter that represents the persona you want to modify:

  • a for all
  • u for the user/owner
  • g for the group
  • o for others/everyone else

Next, you use + or - to add or remove a permission, followed by one or more permission symbols (r, w, x). Finally, specify the file or folder name. Here are a few examples:

1
2
3
chmod a+r filename             # Everyone can now read
chmod a+rw filename # Everyone can now read and write
chmod o-rwx filename # Others cannot read, write, or execute the file

To apply the same permissions to multiple personas, you can combine the letters before the + or - sign:

1
chmod og-r filename            # Others and the group can't read the file anymore

When working with folders, you can apply the permissions recursively using the -r flag.

Numeric arguments provide a faster way to set permissions, but they can be harder to remember. Each permission is represented by a digit: 1 for execute, 2 for write, and 4 for read. These digits are added together to calculate the number value, which can range from 0 to 7. The combinations are as follows:

1
2
3
4
5
6
7
8
0 - No permissions
1 - Execute only
2 - Write only
3 - Write and execute
4 - Read only
5 - Read and execute
6 - Read and write
7 - Read, write, and execute

You use these digits in sets of three to set the permissions for all three groups simultaneously:

1
2
3
chmod 777 filename
chmod 755 filename
chmod 644 filename

Remember, the chmod command is not limited to Linux and macOS; it works in any UNIX environment, including WSL.

Understanding and using the chmod command allows you to manage file permissions effectively.