Set various masks for files and folders

I am writing a bash script to update some files / directories, and I want to run umask in a script to set the default permissions for the files / directories created by the script. I know that umask can set permissions for files and directories, however I need permissions for different files and folders.

I want files to be: -rw----r-- (0604) I want folders to be: drwx-----x (0701) 

Can I do this with umask? If so, how do I do this? If this is not the best way to achieve this? Thank you in advance.

+4
source share
3 answers

An interesting requirement. Currently (at least in bash ) umask is a global parameter, and you cannot set it based on the type of the object.

One solution that comes to mind would be to set umask to a variant of the file and then intercept calls to mkdir (for example, with a user-created mkdir script earlier on the way) to make

 umask 0701 ; /path/to/real/mkdir $1 ; umask 0604 

Thus, if all the creations in the directory are made using mkdir , you can make sure that they use a different umask parameter.

Note that the script should be a little more robust, like restoring the previous umask , rather than forcing it to 0604 and adding some better error checking and possibly the ability to handle multiple arguments.

But in order for everything to start, all the details, the framework above should be enough.

+7
source

umask is an attribute of a process, not a file, that is part of the UNIX architecture and has nothing to do with Bash or any other shell program.

The real problem is that the programs you use do not allow you to change permissions when creating. In C, for example, mkdir has a second parameter, mode.

You do not need to write C, but Python and Perl allow you to use low-level interfaces. Permissions will be changed by the umask process, so if you do not want any changes, set unmask to zero.

 /home/user1> umask 000 /home/user1> python -c 'import os;os.mkdir("mydir",0701)' /home/user1> ls -ld mydir drwx-----x 2 user1 QAPLADV 4096 Sep 16 10:28 mydir /home/user1> python -c 'import os;os.open("myfile",os.O_CREAT,0604)' /home/user1> ls -l myfile -rw----r-- 1 user1 QAPLADV 0 Sep 16 10:32 myfile 

Do not forget that at the moment umask is still 000, you can return it back to its previous value if you are doing any other work in the same process.

Here is the version of Perl if you prefer:

 perl -e "mkdir mydir,0701" perl -MFcntl -e 'sysopen(my $h,"myfile",O_EXCL|O_CREAT,0604)' 

Of course, if you have a large number of files, and you are likely to run this often, then it will be much better for you to write a Perl or Python program to complete the task. Perl or python is called for each file. a little inefficient.

+4
source

Put in user .bashrc:

umask 0222

alias mkdir = 'mkdir -mu = rx, g = rx, o ='

The file will be created using umask 0222, while mkdir will use umask 0227.

0
source

Source: https://habr.com/ru/post/1434444/


All Articles