Ubuntu – Difference between three and four digit file permissions

bashfilespermissions

I was recently wondering what is the difference between three and four digit numerical file permissions. I obtain the numerical permissions by running stat --format "%a" $file_name.What is the difference between 0644 and 644?

Best Answer

The first digit in a four-digit permission is the sum of set user id (4), set group id (2) and sticky (1). A three-digit permission is just like a four-digit permission with the first digit set to zero. Thus:

  • 0644 is exactly the same as 644.
  • 1644 is like 644 but the sticky bit is also set
  • 4644 is like 644 but the set user ID bit is also set.

Examples of uses for the fourth-digit permissions

If a file with set user ID is executed, then it is executed as if by the owner of the file rather than the user doing the executing. Thus, for example, /bin/mount is commonly owned by root and has permissions 4755 where the 4 signifies that, even if executed by a normal user, it will run with the owner's (root's) privileges.

Setting group ID on a directory is useful for sharing files.

The sticky bit is used on directories like /tmp so that all users can create files but prevents non-owners from deleting other people's files. Thus, the permissions of /tmp are typically 1777 where 1 signifies that the sticky bit is set.

Documentation

From man chmod:

A numeric mode is from one to four octal digits (0-7), derived by adding up the bits with values 4, 2, and 1. Omitted digits are assumed to be leading zeros. The first digit selects the set user ID (4) and set group ID (2) and restricted deletion or sticky (1) attributes. The second digit selects permissions for the user who owns the file: read (4), write (2), and execute (1); the third selects permissions for other users in the file's group, with the same values; and the fourth for other users not in the file's group, with the same values.