Set Different Umask For Files And Folders

cryptic ツ picture cryptic ツ · Sep 16, 2012 · Viewed 24.3k times · Source

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

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

Can I do this using umask? If so how do I go about doing it? If not what is the best way to achieve it? Thank you in advance.

Answer

paxdiablo picture paxdiablo · Sep 16, 2012

Interesting requirement. Currently (at least in bash), umask is a global setting and you cannot set it based on object type.

One solution that comes to mind would be to set the umask to the file variant and then intercept calls to mkdir (such as with a user-created mkdir script earlier in the path) to do:

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

That way, assuming all your directory creations are done with mkdir, you can ensure they use a different umask setting.

Note that the script should probably be a little more robust such as 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 that's all detail, the framework above should be enough to get you started.