Bash Permissions and Umask
Bash permissions and umask control who can read, write, or run a file a script creates. Umask removes permission bits at creation time, and chmod sets them exactly afterwards.
Umask 022 leaves shared defaults
The mask is set to 022 before anything is created. The file lands at 644 and the directory at 755.
umask 022
printf 'x\n' > file.txt
mkdir dir1
stat -c %a file.txt
stat -c %a dir1Umask 077 leaves private defaults
The mask is set to 077 before anything is created. The file lands at 600 and the directory at 700, open to the owner only.
umask 077
printf 'x\n' > secret.txt
mkdir priv
stat -c %a secret.txt
stat -c %a privUmask never changes an existing file
The file is created under the strict mask at 600. Relaxing the mask and appending leaves it at 600, and only chmod moves it, to 640.
umask 077
printf 'x\n' > data.txt
stat -c %a data.txt
umask 022
printf 'y\n' >> data.txt
stat -c %a data.txt
chmod 640 data.txt
stat -c %a data.txtExample
umask 077
printf 'token\n' > secret.txt
umask 022
printf 'hello\n' > public.txt
stat -c %a secret.txt
stat -c %a public.txtKey points
- Umask: umask is a mask of permission bits withheld from newly created files and directories.
- File base: new files start from 666 before the mask is applied.
- Directory base: new directories start from 777 before the mask is applied.
- Umask 022: umask 022 leaves files at 644 and directories at 755.
- Umask 077: umask 077 leaves files at 600 and directories at 700, private to the owner.
- Creation only: changing umask never changes files that already exist.
- Chmod exact: chmod sets the mode exactly, whatever the current umask is.
In this example, the strict mask is set first, so the secret file is created private. The mask is then relaxed before the public file is created, so the two files end with different modes in one script.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A script sets umask 077, then creates a file. What mode does the file get?