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 filedindicates a directorylindicates 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:
afor allufor the user/ownergfor the groupofor 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 | chmod a+r filename # Everyone can now read |
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 | 0 - No permissions |
You use these digits in sets of three to set the permissions for all three groups simultaneously:
1 | chmod 777 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.