What's the purpose of setgid directory?
Solution 1:
While a setgid file/binary might not be obviously useful I definitely find the setgid bit very useful applied on directories. Assuming you are parts of different working groups, which each has their own unix (permission) groups. Surely you would then want to put the setgid bit on project folders, making sure that the right group ownership is applied when you create new files, and thereby allowing your colleagues in that project group access to those files?
Solution 2:
The main use is to preserve the group owner of a tree of files:
[lockie@bubbles tmp]$ mkdir dir1 && touch dir1/file && mkdir dir1/dir
[lockie@bubbles tmp]$ mkdir dir2 && chgrp staff dir2 && chmod 2755 dir2 && touch dir2/file && mkdir dir2/dir
[lockie@bubbles tmp]$ ls -al dir1
total 32
drwxrwxr-x 3 lockie lockie 4096 Dec 13 19:32 .
drwxrwxrwt 125 root root 20480 Dec 13 19:32 ..
drwxrwxr-x 2 lockie lockie 4096 Dec 13 19:32 dir
-rw-rw-r-- 1 lockie lockie 0 Dec 13 19:32 file
[lockie@bubbles tmp]$ ls -al dir2
total 32
drwxr-sr-x 3 lockie staff 4096 Dec 13 19:32 .
drwxrwxrwt 125 root root 20480 Dec 13 19:32 ..
drwxrwsr-x 2 lockie staff 4096 Dec 13 19:32 dir < note new dir is g+s, owned by "staff" group, so the setgid behaviour acts recursively
-rw-rw-r-- 1 lockie staff 0 Dec 13 19:32 file < note new file is owned by "staff" group
[lockie@bubbles tmp]$
This tends to be useful in environments where different users will be creating/editing files/dirs under a directory: When all files/dirs share the same group, all users can edit/change the files/dirs (permissions permitting): This avoids situations such as "xyz owns file abc, so I can't edit it".
An alternative to using setgid in this way is the grpid filesystem mount option.
From man mount:
grpid or bsdgroups / nogrpid or sysvgroups
These options define what group id a newly created file gets. When grpid is set, it takes the group id of the directory in which it is created; otherwise (the default) it takes the fsgid of the current process, unless the directory has the setgid bit set, in which case it takes the gid from the parent directory, and also gets the setgid bit set if it is a directory itself.
When enabled, files/dirs created on a grpid mounted filesystem also inherit the group of the parent directory:
[lockie@bubbles ~]$ mount | grep /home
/dev/mapper/VolGroup00-home on /home type ext3 (rw,grpid)
[lockie@bubbles ~]$ mkdir dir3 && touch dir3/file && mkdir dir3/dir
[lockie@bubbles ~]$ ls -al dir3
total 12
drwxrwxr-x 3 lockie users 4096 Dec 13 19:37 .
drwxrwxr-x 12 lockie users 4096 Dec 13 19:37 ..
drwxrwxr-x 2 lockie users 4096 Dec 13 19:37 dir < inherited "users" group from parent dir
-rw-rw-r-- 1 lockie users 0 Dec 13 19:37 file < inherited "users" group from parent dir
[lockie@bubbles ~]$
I've found using grpid option appropriately reduces the chance for human error (since the filesystem does the work, regardless of dir permissions).