What is umask, and how does it decide default file permissions?
umask is a mask of permission bits that are removed from the defaults for newly created files and directories. Files start from 666 and directories from 777, so a umask of 022 gives files 644 and directories 755.
Explain it simply
Imagine a stencil. New files start with a wide-open pattern, and the umask is a stencil that blocks some of it. Whatever the stencil covers is removed.
Defaults before the mask: directories 777, files 666 (files never get execute automatically, for safety). Then the umask bits are subtracted from those.
With the common umask 022: directory 777 minus 022 gives 755, file 666 minus 022 gives 644. With the stricter umask 077 you get 700 and 600: only the owner has access.
Strictly it is a bitwise AND with the inverse of the mask, not plain subtraction, but for normal values the result is the same. Set it per session with umask 027, or permanently in ~/.bashrc or /etc/profile.
Example
umask
# 0022
touch a.txt; mkdir d
ls -ld a.txt d
# -rw-r--r-- ... a.txt
# drwxr-xr-x ... d
umask 077; touch secret.txt; ls -l secret.txt
# -rw------- ... secret.txtWhat to say in the interview
"umask removes permission bits from the defaults of 666 for files and 777 for directories. With 022 I get 644 and 755; with 077 only the owner can access new files. I set a stricter umask for scripts that create sensitive files."
Common mistakes
- Applying umask to an existing file; it only affects newly created ones.
- Subtracting from 777 for files; files start at 666.