In a Unix/Linux operating systems, chmod
is the command, which may change the access permissions to files and directories.
It works if the user has the right to change the file or directory permission.
When you use ll
or ls -l
for files, or ls -ld
for directories, you will see access permissions as 10 characters before the name of the file or directory. The first character to the left is d
for directories, and -
for files.
To understand the file permission, consider the following table.
- | rwx | rwx | rwx |
---|---|---|---|
user | group | other |
where, r = read, w = write, and x = execute
Any of these characters being -
is the lack of that specific permission.
There are two ways of changing file permission.
Symbolic way
Considering u = user, g = group, o = others, and a = all, you can add (+) or deny (-) permissions with different combinations. Examples:
chmod a-x file.txt # deny execute permission to all users
chmod g+rw file.txt # add read & write permissions to group members
chmod g=rw file.txt # like the previous line
You can use =
instead of +
, if you have more than one mode in the left or the right side. Example:
chmod ug=rw file.txt # add read & write permissions for user and group members.
To apply changes to a directory and its contents recursively, use option -R
.
chmod -R u+w directory # add write permission to the directory (to be able to add/remove files), and all its contents
Numeric way
r | w | x | r | w | x | r | w | x |
---|---|---|---|---|---|---|---|---|
400 | 200 | 100 | 40 | 20 | 10 | 4 | 2 | 1 |
The sum of these numbers is 777, which means all permissions given to a file for all users.
chmod 777 file.sh
Summing numbers for specific permissions, you will get the number for the desired permission.
Assume you do not want to give an execute permission for a file to any user, because it is not a program or script, and you want to give read & write permissions to user and group members, and only read permission to others. This is equivalent to: rw-rw-r--
400 + 200 + 0 + 40 + 20 + 0 + 4 + 0 + 0 = 664
chmod 664 file.txt
For not thinking about the right symbolic combination, or number, I wrote the following script, which requires the file or directory name (for example: fileordirname) and the permission mode. If you save the code in a file called (for example) permission.sh, You can run it like this:
. permission.sh rwxrw-r-- fileordirname
Do not forget to give execute permission to the script file itself!