0
0
Linux-cliConceptBeginner · 3 min read

What is setgid in Linux: Explanation and Usage

In Linux, setgid is a special permission bit that, when set on a directory or executable, causes files created inside to inherit the group ownership or causes the executable to run with the group ID of the file owner. It helps manage group permissions and collaboration by controlling group access automatically.
⚙️

How It Works

Think of setgid as a rule that changes how group ownership works for files and programs. When you set this bit on a directory, any new file created inside will automatically belong to the directory's group, not the creator's default group. This is like a shared folder where everyone’s files belong to the same team, making collaboration easier.

For executable files, setgid means the program runs with the permissions of the file’s group owner, not the user who runs it. This allows users to perform tasks with group privileges temporarily, similar to borrowing a team badge to access shared resources.

💻

Example

This example shows how to set the setgid bit on a directory and check its effect on new files created inside.
bash
mkdir shared_folder
chgrp developers shared_folder
chmod 2775 shared_folder
ls -ld shared_folder

# Now create a file inside
cd shared_folder
touch example.txt
ls -l example.txt
Output
drwxrwsr-x 2 user developers 4096 Apr 27 12:00 shared_folder -rw-r--r-- 1 user developers 0 Apr 27 12:01 example.txt
🎯

When to Use

Use setgid on directories when you want all files created inside to share the same group ownership. This is common in team projects where multiple users need to read and write files without changing permissions manually.

Use setgid on executables when a program needs to run with group privileges different from the user’s own. For example, some network or system tools require group access to perform tasks safely without giving full user permissions.

Key Points

  • setgid on directories: new files inherit the directory's group.
  • setgid on executables: program runs with the file's group ID.
  • Helps manage group collaboration and permissions automatically.
  • Improves security by limiting privilege escalation to group level.

Key Takeaways

Setgid ensures files inside a directory inherit the directory’s group ownership.
Setgid on executables runs the program with the file’s group permissions.
It simplifies group collaboration by automating group access control.
Use setgid to safely share resources among users in the same group.
Check permissions with ls -l to confirm setgid is set (look for 's' in group bits).