How to Change File Permissions in Linux
Linux is an OS in which we can have multiple users. So, we need to manage access permissions for files in Linux. If a user does not have permissions to access and edit a file, sometimes we may get Permission denied error. We can change file permissions in Linux using the chmod command-line utility.
View Permissions of a Linux File
To view permissions of all the files and directory in the current working directory, we use the ls -l command.
ls -l
Output:
-rw-rw-r-- 1 zeppy zeppy 123 Oct 4 20:47 1.sh
-rw-rw-r-- 1 zeppy zeppy 46 Sep 30 20:36 file.txt
The portion at the beginning of each file represents the permission for each specific file in the location. In the output, -rw-rw-r-- represents file permission.
-at the beginning represents that the content is a filerw-represents permissions foruserrw-represents the permission foruser-groupr--represents the permissions forothers.
The r represents the read permission, w represents the write permission, x represents the execute permission, and - represents no permission.
As the output shows, user and group have read and write permissions only but not execute permission, while others have only read permissions for both the file in the current working directory.
Change File/Directory Permissions With the chmod Command
Syntax
chmod permissions filename
Here, permissions represent the permission we want to set, and filename represents the name of the file whose permission is to be set.
We can represent the permissions using either the absolute mode or using the symbolic mode.
Example: Set Permissions for Files Using the chmod Command
chmod 760 file.txt
It sets the read, write and execute permissions to owner or the user, read and write permissions to the group, and no permissions to the others for the file file.txt. Here, the permissions are represented using the absolute mode.
chmod u=rwx,g=rw,o=--- file.txt
It sets the read, write and execute permissions to owner or the user, read and write permissions to the group, and no permissions to the others using the symbolic mode.
Example: Set Permissions for Directories Using the chmod Command
To set the permissions for all the files inside a directory, we use the chmod command with -R or --recursive option.
chmod -R 760 testdir
It sets the read, write and execute permissions to owner or the user, read and write permissions to the group, and no permissions to the others for the directory testdir using the absolute mode.
chmod -R u=rwx,g=rw,o=--- testdir
It sets the read, write and execute permissions to owner or the user, read and write permissions to the group and no permissions to the others for the directory testdir using the symbolic mode.
Suraj Joshi is a backend software engineer at Matrice.ai.
LinkedIn