1

I have an octal representing Linux file permissions. The permissions are currently, I.E 0o640 and I want to set the group bit to 6 (so 0o660). I saw that I can set the bit in the nth place here but the results I get are peculiar, I guess that it is because of the octal representation.

I Tried:

perm = 0o640
# Set the bit in the 2nd place (index 1) to 6. 
new_perm = perm | (6<<1)
# new_perm is now 0o634 (wanted 0o660).

I'm doing something wrong I guess...

I also wonder what is the advantage of using octal instead of regular integers in Python when working with file permissions.

Thanks!

Alastair McCormack
  • 26,573
  • 8
  • 77
  • 100
Gal Shahar
  • 2,695
  • 1
  • 21
  • 29
  • 1
    It's a Unix tradition to use Octal representation - some argue that it's simple to read: https://www.quora.com/Why-do-nix-systems-use-the-octal-number-system-for-representing-file-directory-permissions-Why-is-it-helpful. In Python, there's a number of file perm contestants you can use to easily set perms using `os.chmod`: https://stackoverflow.com/questions/16249440/changing-file-permission-in-python – Alastair McCormack Apr 18 '20 at 12:11

1 Answers1

4

<< shift number by a bit. for the answer you want you should shift 0o600 by 3.

perm = 0o600
new_perm = (perm  & 0o707) | (6<<3)
print(new_perm == 0o660) # True

According to comment we should first make the bits we want to zero and then use |.

(perm & 0o707) This part of code make that happens.

SMortezaSA
  • 589
  • 2
  • 15
  • Thanks! Can you explain why 3? – Gal Shahar Apr 18 '20 at 11:42
  • 3
    Because an each octal number is 3 bits number for example `0o6` equals with `0b110`. – SMortezaSA Apr 18 '20 at 11:45
  • 1
    @GalShahar note that this doesn't work with other parameters, as `|` always "turns on" bits. to actualy overwrite the entire octal digit you first need to 0 it and then use `|` to set the bits you want on. – Adam.Er8 Apr 18 '20 at 12:04
  • @GalShahar Yes, you're right, in this case those digits was 0, but we want to work with any perm we should make them to `0`. – SMortezaSA Apr 18 '20 at 12:11