Respect umask
like chmod +x
man chmod
says that if augo
is not given as in:
chmod +x mypath
then a
is used but with umask
:
A combination of the letters ugoa controls which users' access to the file will be changed: the user who owns it (u), other users in the file's group (g), other users not in the file's group (o), or all users (a). If none of these are given, the effect is as if (a) were given, but bits that are set in the umask are not affected.
The goal of this is so that you don't accidentally give too many permissions. umask determines the default permissions of a new file, e.g. with a umask of 0077
, touch newfile.txt
produces permissions rw
for the current user because the 77 would exclude group and other (x is not given by default by touch anyways though). And chmod +x
would similarly only add +x
for user, ignoring group and other due to the 0011
part of the mask: you would need chmod o+x
, chmod g+x
, chmod go+x
or chmod a+x
to force them to be set.
Here is a version that simulates that behavior exactly:
#!/usr/bin/env python3
import os
import stat
def get_umask():
umask = os.umask(0)
os.umask(umask)
return umask
def chmod_plus_x(path):
os.chmod(
path,
os.stat(path).st_mode |
(
(
stat.S_IXUSR |
stat.S_IXGRP |
stat.S_IXOTH
)
& ~get_umask()
)
)
chmod_plus_x('.gitignore')
See also: How can I get the default file permissions in Python?
Tested in Ubuntu 16.04, Python 3.5.2.