Gal Shahar
Gal Shahar

Reputation: 2815

How to bitshift in Python to manipulate a filesystem octal

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!

Upvotes: 1

Views: 301

Answers (1)

SMortezaSA
SMortezaSA

Reputation: 589

<< 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.

Upvotes: 4

Related Questions