Permissions & Ownership

3 minuti

View permissions

To check some file permissions you can run the ls command with -l option:

ls -l
 
# Output
drwxr-xr-x. 4 root root    68 Jun 13 20:25 tuned
-rw-r--r--. 1 root root  4017 Feb 24  2022 vimrc

Reading the first line of output we have: drwxr-xr-x. where:

  • the first character is the file type, in this case d that stands for directory. Another base example of file type is - that indicates a normal file
  • the next 9 characters are meant to be read 3 by 3. The first 3 dictate the permissions for owner of the file, the following 3 the permissions applies to the user group that owns the file and the last 3 the permissions for other users.
    • r for reading
    • x for executing
    • w for writing
    • - if the permission is not granted

Octal values

When Linux file permissions are represented by numbers, it’s called numeric mode. In numeric mode, a three-digit value represents specific file permissions (for example, 744.) These are called octal values. The first digit is for owner permissions, the second digit is for group permissions, and the third is for other users. Each permission has a numeric value assigned to it:

  • r (read): 4
  • w (write): 2
  • x (execute): 1 For example, drwxr-xr-x in numeric mode is 755, because:
  • Owner: rwx = 4+2+1 = 7
  • Group: r-x = 4+0+1 = 5
  • Others: r-x = 4+0+1 = 5

Change permissions

To change the permissions from a given file, you can use the chmodcommand, for example:

ls -l
 
# Output
-rw-r--r--. 1 root  root  0  6 Nov 10:00 my-script.sh
 
chmod +x my-script.sh
ls -l
 
# Output
-rwxr-xr-x. 1 root  root  0  6 Nov 10:00 my-script.sh

This command add the execution permission to the given file for all users. You can use the octal values to change permissions as well:

ls -l
 
# Output
-rwxr-xr-x. 1 root  root  0  6 Nov 10:00 my-script.sh
 
chmod 755 my-script.sh
ls -l
 
# Output
-rwxr-xr-x. 1 root  root  0  6 Nov 10:00 my-script.sh

Change ownership

Ownership is changed with the chown command. The owner alone can hand a file away (while root can change anything), and only root can transfer group ownership to a group the user doesn’t belong to:

ls -l my-script.sh
 
# Output
-rwxr-xr-x. 1 root  root  0  6 Nov 10:00 my-script.sh
 
chown carloberd my-script.sh             # change the owner
chown carloberd:carloberd my-script.sh   # change owner and group at once
chgrp devs my-script.sh                  # change only the group
ls -l my-script.sh
 
# Output
-rwxr-xr-x. 1 carloberd  devs  0  6 Nov 10:00 my-script.sh

With the -R flag the change is applied recursively to every file and directory inside a folder — use it with care. The permission bits shown above interact with these special cases: see SUID, SGID & File Capabilities for the fourth octal digit.