Using SGID to Control Group Ownership of Directories

1. My login id is paul and my primary group is webdev. I’m also a member of several other groups including staff. By default, any file (including a directory) I create will be marked with the group webdev (my primary group) .
$mkdir mydir
$ls -ld mydir
drwxr-xr-x 2 paul webdev 512 May 06 11:14 mydir
2. If I want my colleagues in staff to write to this directory, I need to change the group on the directory to staff and set the permissions to write for the group.
$chgrp staff mydir
$chmod 775 mydir
$ls -ld mydir
drwxrwxr-x 2 paul staff 512 May 06 11:14 mydir
3. Now staff can write to the directory, but we still have a problem if staff is not everyone’s primary group. Look what happens when paul, a member of staff who’s primary group is webdev, creates a file (paulfile) in the directory (mydir):
$touch mydir/paulfile
$ls -l mydir
total 0
-rw-r–r– 1 paul webdev 0 May 06 11:20 paulfile
At this point, I could issue the chgrp command and set the permissions manually.
There’s another solution.
4. The owner of the directory can set the SGID bit and all files subsequently placed there will have the group id of the directory automatically.
Make sure the group name is set first on the directory.
Give the group write permission on the directory.
Issue the command chmod g+s directory_name
$chmod g+s mydir
$ls -ld mydir
drwxrwsr-x 2 paul staff 512 May 06 11:20 mydir
Notice the “s” next to the group permissions in the listing.
(You can reverse it with chmod g-s)
5. Now, when I create a file in the directory, it will be marked with staff as the group, even though my primary group is webdev.
$touch mydir/anotherfile
$ls -l mydir
total 0
-rw-r–r– 1 paul webdev 0 May 06 11:20 paulfile
-rw-r–r– 1 paul staff 0 May 06 11:30 anotherfile
Notice that the pre-existing file “paulfile” didn’t change. I’d still have to issue chgrp on it.
Of course, I still need to set the group permissions to write if I want others to be able to edit these files.
What if you:
ftp a file into an SGID directory? — It inherits the GID of the directory, as above.
mv a file into an SGID directory? — It keeps its current GID.
cp a file into an SGID directory? — It inherits the GID of the directory.
mkdir inside an SGID directory? — It inherits the GID of the enclosing directory and is also marked SGID.

Leave a Reply

Your email address will not be published. Required fields are marked *