If I want specific Linux/Unix permissions for newly created files how do I calculate what umask value to use?

69 views Asked by At

How do I calculate the umask absolute value I would need if I wanted Linux/Unix permissions for newly created files to be some arbitrary value xyz?

I know how to determine what file permissions a system will end up with if I use a specific absolute value of umask. For example if the system default file permissions value is 666 and I apply a umask absolute value of 022 I know that the resulting permissions value for a newly created file is 644 (calculated by ANDing NOT(022) with 666).

But what about the inverse problem?

It seems to me that the only way to determine what umask absolute value you must employ to get a specific permissions value for newly created files is to create a table. One column would have all possible umask values (so a big table!) and the second column would contain their corresponding new-file permission values (for any given system default file-permissions value).

Am I right?

2

There are 2 answers

4
knittl On BEST ANSWER

required_umask = ~expected_mode & ~111 (or & 666) should do the trick (for files only, directories don't start with 0666 but with 0777)

  ~644 & ~111
=  133 &  666
=  022
  ~666 & ~111
=  111 &  666
=  000
  ~400 & ~111
=  377 &  666
=  266

If you build a table, it's not going to be too large. For files, there are only 4**3 = 64 distinct umask values (000, 002, 004, 006, 020, 022, 024, 026, 040, 042, ...). Even if you consider all 8 possible values per digit, it's "only" 512 entries (unhandy for a human, but not really that large).

0
Toby Speight On

As a programmer, you don't set the umask. That's the user's mask of file permissions.

Just use the permissions you think appropriate in your open() call, and then the users are able to mask out unwanted permissions by setting umask according to their needs.