File Permissions
If you've run ls -al
in your terminal, you may have seen output like this:
drwxr-xr-x 13 yourname staff 416 Jul 19 22:59 .git
Aside: If this looks unfamiliar to you, try to follow these steps to get some background info.
1. Run `man ls` in your terminal.
2. Scroll to the section for the flag `-l`.
3. For Unix systems, scroll to the `The Long Format subsection` referenced in Step 2.
We're going to be looking at just this part: drwxr-xr-x
.
Specifically, just the last 9 characters: rwxr-xr-x
.
[ d ] [ rwx ] [ r-x ] [ r-x ]
│ │ │ └─ Others
│ │ └──────── Group
│ └───────────────── Owner (aka "user")
└──────────────────────── File type
The first character, d
means that .git
is a directory.
The next nine characters, rwxr-xr-x
, denotes the file permissions of .git
.
rwx
means the owner can read, write, and execute. The next r-x
means
the group can read and execute. And the last r-x
means that all others
can also read and execute.
In programming, these file permissions are often represented in octal,
or base-8. For example, rwxr-xr-x
can be represented as 755
.
To perform this translation, it helps to translate the characters to binary
first and then to octal.
Permission | Binary | Octal |
---|---|---|
rwxr-xr-x |
111 101 101 |
755 |
Each character gets replaced with 1
, and each -
gets replaced with 0
.
So rwx
becomes 111
, and r-x
becomes 101
in binary.
Who | Permissions | Binary |
---|---|---|
Owner | rwx |
111 |
Group | r-x |
101 |
Others | r-x |
101 |
Now to get to the octal representation, it helps to look at each group of
three binary digits separately. First take 111
and read the digits backwards
from right to left. The first 1
represents the one's place in binary. This digit
is "on" so we have 1. The next 1
represents the two's place in binary. This digit
is also "on" so we have 2. The next 1
represents the four's place in binary. This
digit is also "on" so we have 4
. If we add up 1 + 2 + 4
, we get 7
.
1 1 1
2² + 2¹ + 2⁰
= 4 + 2 + 1
= 7
We can do the same thing for 101
. Remember to read these digits backwards from
right to left. The first 1
represents the one's place in binary. This digit
is "on" so we have 1. The next 1
represents the two's place in binary. This digit
is "off" so we have 0. The next 1
represents the four's place in binary. This
digit is "on" so we have 4
. If we add up 1 + 0 + 4
, we get 5
.
1 0 1
2² + 2¹ + 2⁰
= 4 + 0 + 1
= 5
So this is how we get from rwxr-xr-x
(friendly readable format) to 111 101 101
(binary representation) to 755
(octal representatation).