setgid
What is setgid?
setgid
(short for set group ID) is a special permission bit on Unix filesystems that lets you configure how new files and directories inherit group ownership.
Its exact behaviour depends on whether it’s set on a file or a directory but you will almost always set it only on directories so let’s focus on that use case.
How setgid affects directory permissions
When you set the setgid
on a directory, any new files or subdirectories created inside will inherit the directory’s group, instead of the creating user’s default group (the default behaviour).
This is useful when you want a particular directory and its subdirectories & files to always have the same group, regardless of who created the subdirectories or files.
For example, you might want to configure things so that the var/cache
folder in a Symfony project and all its subfolders and files always have the group www-data
.
# Assign correct user (root) & group (www-data)
sudo chown -R root:www-data /var/cache
# Ensure owner and group have read, write, and execute
# permissions. Also set the setgid bit to ensure future files
# or subdirectories always have the group www-data
sudo chmod 2775 /var/cache
Here, the first number 2
in chmod 2775
sets the setgid bit on the folder which in plain terms means you tell your OS:
Hey, make sure any files or subdirectories created inside /var/cache always have the group www-data, regardless of which user created those subdirectories or files.
Recipes
Set setgid
for directory
sudo g+s <dir>
This will set the setgid bit on <dir>
so that any files and folders created inside it always inherit the group
that it has currently.
Remove setgid
for directory
sudo g-s <dir>
Check if a directory has the setgid set
ls -ld <dir>
If the <dir>
has an s
in the group permissions, it has the setgid bit.