what is the difference between umask and chmod

Solution 1:

The difference is that umask entails only new files. As you stated, umask sets the default permissions that a file/directory will have on creation time, but afterwards umask doesn't affect them anymore.

chmod, however, needs the file be created prior to be run.

Therefore, if you run umask, it will have no effect at all on existing files.

Solution 2:

umask is very different from chmod, actually.

  1. An important difference hasn't been mentioned yet: chmod sets, but umask clears (restricts) permission bits. That's why it's called "mask" (as in "bitmask").

  2. As David wrote, umask is a (process-level) configuration setting, so it's not applied on any specific files (as opposed to chmod).

  3. Which brings us to another important point: umask is not limited to files. It's also applied when creating directories. (See also e.g. this answer.)

  4. Also important, that the chmod command itself is not affected by the currently configured umask.

Now, to your example of what would umask 666 do:

It will tell the current process (for example your shell) that any new filesystem objects should be created with the R+W bits (4 + 2 = 6) removed (from whatever permissions implicitly or explicitly requested upon creation). (So, 666 is not a very practical value, since it only allows the X (execute) bits to be set, but for unreadable files...)

E.g.:

$ touch foo; ls -la foo
-rw-r--r-- ... foo   <-- default permissions

$ umask 666
$ touch bar; ls -la bar
---------- ... bar   <-- perms. after the new umask (restriction) is set
$ mkdir foodir; ls -la | grep foodir
d--x--x--x ... dir   <-- not very practical for dirs, either

$ chmod 777 bar; ls -la bar
-rwxrwxrwx .... bar* <-- chmod happily ignores the current umask

$ umask 022
$ touch bong; ls -la bong
-rw-r--r-- ... bong  <-- (so, it seems this was the default umask)

$ chmod 666 bong; ls -la bong
-rw-rw-rw- ... bong  <-- no surprise of any kind here

Solution 3:

UMASK = chmod 777 - umask permissions

umask 022 => 777 - 022 => chmod 755
umask 077 => 777 - 077 => chmod 700
umask 002 => 777 - 002 => chmod 775
umask 007 => 777 - 007 => chmod 770
umask 027 => 777 - 027 => chmod 750
umask 177 => 777 - 177 => chmod 600

Something like that.