The setgid bit can also be used on directories. If a directory has the setgid bit and is group writable, if a user (not the directory owner) with a different primary group writes a file in that directory and but has supplemental membership in the group that owns the directory, the new file gets the same group ownership as the directory. Not the primary group of the user writing the file. Very handy in some instances.
As an example we have two users, foo and bar. foo's primary group is also foo. bar's primary group is bar, but is a supplemental member of foo.
foo@valhalla:~$ id
uid=1002(foo) gid=1002(foo) groups=1002(foo)
bar@valhalla:~$ id
uid=1003(bar) gid=1003(bar) groups=1003(bar),1002(foo)
foo@valhalla:~$ grep foo /etc/group
foo:x:1002:bar
foo@valhalla:~$ grep bar /etc/group
foo:x:1002:bar
bar:x:1003:
I will create a directory /tmp/foodir and make it setgid and group writable.
foo@valhalla:~$ mkdir /tmp/foodir
foo@valhalla:~$ chmod g+ws /tmp/foodir
foo@valhalla:~$ ls -ld /tmp/foodir
drwxrwsr-x 2 foo foo 4096 Jun 6 19:30 /tmp/foodir
I will now touch a file in /tmp/foodir as the user bar.
bar@valhalla:~$ touch /tmp/foodir/barfile
bar@valhalla:~$ ls -l /tmp/foodir/barfile
-rw-r--r-- 1 bar foo 0 Jun 6 19:32 /tmp/foodir/barfile
Notice the group ownership of /tmp/foodir/barfile is foo, not bar which is the user bar's primary group.
Now we try the other way around, but foo isn't a member of group bar.
bar@valhalla:~$ mkdir /tmp/bardir
bar@valhalla:~$ chmod g+ws /tmp/bardir
bar@valhalla:~$ ls -ld /tmp/bardir
drwxrwsr-x 2 bar bar 4096 Jun 6 19:34 /tmp/bardir
Look what happens when we try to touch a file as foo. It's what you should expect, a permission error.
foo@valhalla:~$ touch /tmp/bardir/foofile
touch: cannot touch '/tmp/bardir/foofile': Permission denied
And for one last step. We'll touch a file in /tmp (a not setgid directory that bar can write to) as bar.
bar@valhalla:~$ ls -ld /tmp/barfile
-rw-r--r-- 1 bar bar 0 Jun 6 19:36 /tmp/barfile
The owner and group are both bar.