Website Vidya
SecurityStep-by-Step Guide

How to List Groups in Linux (groups, id, and getent group)

Learn list groups in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
11 min read
PDF Cheat Sheet
How to List Groups in Linux (groups, id, and getent group)
AI Executive SummaryWebsiteVidya AI

11 min read

Learn list groups in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What groups Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Knowing how to list groups in Linux involves two distinct administrative tasks: checking which groups a specific user belongs to (groups username or id username), and enumerating every group registered across the operating system (getent group or reading /etc/group). Because Linux discretionary access control (DAC) relies heavily on primary and supplementary Group IDs (GIDs) to control access to shared directories, device nodes (/dev/kvm, /dev/ttyUSB0), sockets (/var/run/docker.sock), and sudo policies, auditing group memberships is a daily task for sysadmins and security engineers.

The groups utility, included in GNU coreutils, provides the fastest way to display the group memberships of your active session or any specified username. However, understanding the subtle difference between running groups with no arguments (which inspects the active kernel process credentials via getgroups(2)) versus groups username (which queries /etc/passwd and /etc/group via NSS) explains why newly added groups sometimes appear in one output but not the other.

When you need to list all groups on the server or find every user who belongs to a specific group like sudo, wheel, or docker, combining getent group with awk, cut, or grep gives you complete visibility into both supplementary members in /etc/group and users whose primary GID in /etc/passwd points to that group.

Advertisement
How to List Groups in Linux (groups, id, and getent group) — syntax, flags, and practical terminal workflow diagram
How to List Groups in Linux (groups, id, and getent group) — command syntax, key options, and production workflow reference.

What groups Does and When to Use It

Linux stores local group definitions in /etc/group, a world-readable (0644) flat text file where each line contains four colon-separated fields: group_name:password_placeholder:GID:user_list. The fourth field (user_list) is a comma-separated list of usernames that belong to the group as a supplementary group. Importantly, a user whose primary group (field 4 of /etc/passwd) is set to that GID is often NOT repeated in the fourth field of /etc/group. Therefore, looking only at the end of a line in /etc/group only shows supplementary members unless you also cross-reference primary GIDs in /etc/passwd.

Just like user resolution, Linux resolves group names and GIDs through the Name Service Switch (/etc/nsswitch.conf, line group: files systemd sss). Running getent group calls getgrent() in glibc to enumerate local groups from /etc/group alongside centralized directory groups from SSSD, FreeIPA, or Active Directory.

Linux enforces discretionary access control (DAC) by evaluating the effective User ID (EUID), effective Group ID (EGID), and supplementary groups against inode permission bits. When groups executes, the Virtual File System (VFS) and active Linux Security Modules (SELinux or AppArmor) validate the caller's privileges before committing changes to disk or account databases.

Availability and Installation Across Linux Distributions

The groups utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether groups is installed and inspect which binary path and version your shell resolves:

type -a groups
groups --version 2>/dev/null || man -f groups

# Illustrative output (reviewed against documentation)
groups is /usr/bin/groups
groups (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

groups [USERNAME]... | getent group [GROUPNAME | GID]

The groups command accepts zero or more USERNAME operands: groups [OPTION]... [USERNAME].... With no USERNAME, it prints the space-separated list of groups active in the calling process's credentials. With one or more USERNAME arguments, it queries the NSS database for each user and prints username : primary_group supplementary_group1 ....

For scripting and programmatic checks, the POSIX standard id utility (id -Gn [USERNAME] for group names, id -G [USERNAME] for numeric GIDs, and id -gn [USERNAME] for only the primary group name) is preferred over groups because its output format never prepends username : when a username argument is passed.

  • 0 — Group memberships or group database entries printed successfully.
  • 1 — Specified username does not exist (when using groups or id).
  • 2 — Specified group name or GID was not found in the NSS database (when using getent group KEY).

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
(no args)groupsPrint all group names active in the current shell process's kernel credential list.
USERNAMEgroups USERNAMEQuery NSS (/etc/passwd and /etc/group) to list all groups assigned to USERNAME.
-Gid -G [USER]Print all numeric Group IDs (primary and supplementary) for the current or specified user.
-nGid -nG [USER]Print all human-readable group names (without any 'username :' prefix) for reliable scripting.
-gnid -gn [USER]Print only the user's primary group name.
groupgetent group [KEY]Enumerate all system and network groups, or inspect a specific group by name or numeric GID.
-gcompgen -gBash built-in completion flag that outputs all group names known to the system, one per line.
-glslogins -gDisplay a formatted summary table of groups and their supplementary member counts.

When writing shell scripts that test whether a user belongs to a specific group, avoid parsing groups username because GNU coreutils outputs username : group1 group2 whereas some BSD/BusyBox implementations omit the username : prefix. Instead, use id -nG username | grep -qw "groupname", which produces a consistent space-delimited list across all POSIX systems.

Advertisement

When listing all groups across a machine, getent group is superior to cat /etc/group because it includes network groups and lets you look up specific groups by either name (getent group sudo) or numeric GID (getent group 27).

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. List Groups for the Current Logged-In User

Run groups or id -nG without arguments to see which groups are active in your current terminal session.

groups
id

# Illustrative output (reviewed against documentation)
alex adm sudo docker developers
uid=1001(alex) gid=1001(alex) groups=1001(alex),4(adm),27(sudo),998(docker),1005(developers)

groups prints a concise list of group names, while id shows both the numeric GIDs and names, clearly distinguishing the primary group (gid=1001(alex)) from the complete group set (groups=...).

2. List All Groups a Specific User Belongs To

Pass one or more usernames to groups (or id -nG) to inspect their group memberships configured on disk.

groups alex priya www-data
id -nG priya

# Illustrative output (reviewed against documentation)
alex : alex adm sudo docker developers
priya : priya sudo developers
www-data : www-data
priya sudo developers

The first group listed right after the colon (alex : alex) is always the user's primary group from /etc/passwd, followed by supplementary groups from /etc/group.

3. List All Groups on the Linux System (getent group)

To view every group defined on the system along with its numeric GID and supplementary member list, run getent group.

getent group | head -n 8
getent group | tail -n 4

# Illustrative output (reviewed against documentation)
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:syslog,ubuntu,alex
tty:x:5:
disk:x:6:
lp:x:7:
sudo:x:27:ubuntu,alex,priya
docker:x:998:alex
alex:x:1001:
developers:x:1005:alex,priya

Each line shows group_name:x:GID:members. Notice how adm, sudo, docker, and developers list their supplementary members in the fourth field.

4. List Only Group Names Alphabetically and Count Total Groups

Extract the first column of getent group using cut -d: -f1 to get a clean list of group names or count how many groups exist.

getent group | cut -d: -f1 | sort | head -n 8
echo "Total system groups: $(getent group | wc -l)"

# Illustrative output (reviewed against documentation)
adm
alex
audio
backup
bin
cdrom
crontab
daemon
Total system groups: 74

Using cut -d: -f1 strips away the password placeholder, numeric GID, and member list, leaving only the group name.

5. List All Members of a Specific Group (e.g., sudo or docker)

Query a specific group name with getent group to inspect its GID and supplementary members.

getent group sudo docker developers

# Illustrative output (reviewed against documentation)
sudo:x:27:ubuntu,alex,priya
docker:x:998:alex
developers:x:1005:alex,priya

Passing multiple group keys to getent group prints only the matching lines without needing grep.

6. List Only Non-System / Regular Groups (GID >= 1000)

Just as UID_MIN separates human users from system daemons, GID_MIN (typically 1000) separates user-created groups from OS system groups.

getent group | awk -F: '$3 >= 1000 && $3 < 60000 { printf "%-18s GID=%-6s MEMBERS=%s\n", $1, $3, $4 }'

# Illustrative output (reviewed against documentation)
ubuntu             GID=1000   MEMBERS=
alex               GID=1001   MEMBERS=
priya              GID=1002   MEMBERS=
developers         GID=1005   MEMBERS=alex,priya
webapps            GID=1006   MEMBERS=

Filtering $3 >= 1000 && $3 < 60000 shows user-private groups (ubuntu, alex, priya) and custom organizational groups (developers, webapps).

Real-World Workflows, Pipelines, and Shell Automation

Find ALL Members of a Group (Both Primary and Supplementary)

A common trap when auditing /etc/group is that users whose primary group (gid in /etc/passwd) is set to webapps (GID 1006) do not appear in the fourth field of /etc/group. This script combines both /etc/passwd primary GIDs and /etc/group supplementary members for a complete audit.

#!/usr/bin/env bash
set -euo pipefail

GRP_NAME="${1:-developers}"
GRP_LINE="$(getent group "$GRP_NAME")"
GID_NUM="$(echo "$GRP_LINE" | cut -d: -f3)"
SUPP_USERS="$(echo "$GRP_LINE" | cut -d: -f4 | tr ',' ' ')"
PRIM_USERS="$(getent passwd | awk -F: -v g="$GID_NUM" '$4 == g {print $1}')"

echo "=== Complete Membership for $GRP_NAME (GID $GID_NUM) ==="
printf '%s
' $PRIM_USERS $SUPP_USERS | sort -u

# Illustrative output (reviewed against documentation)
=== Complete Membership for developers (GID 1005) ===
alex
priya

By looking up the group's numeric GID ($GID_NUM) and scanning field 4 of getent passwd alongside field 4 of getent group, this workflow guarantees no primary-group member is ever missed during a security review.

Privileged Group Compliance Audit Across a Server

Generate a clean security report of all sensitive administrative and container groups (root, sudo, wheel, adm, docker, lxd, disk) and their members.

for grp in root sudo wheel adm docker lxd disk; do
  if line=$(getent group "$grp" 2>/dev/null); then
    gid=$(echo "$line" | cut -d: -f3)
    members=$(echo "$line" | cut -d: -f4)
    printf "%-10s (GID %-4s): %s
" "$grp" "$gid" "${members:-<none>}"
  fi
done

# Illustrative output (reviewed against documentation)
root       (GID 0   ): <none>
sudo       (GID 27  ): ubuntu,alex,priya
adm        (GID 4   ): syslog,ubuntu,alex
disk       (GID 6   ): <none>
docker     (GID 998 ): alex

Iterating over known high-privilege group names and printing <none> when the supplementary list is empty provides an instant snapshot for CIS or SOC 2 compliance checks.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding groups inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

During privilege escalation reconnaissance, attackers routinely run id, groups, and getent group to check whether the compromised account belongs to sudo, wheel, docker, adm, systemd-journal, disk, or video. Membership in adm or systemd-journal grants read access to system logs in /var/log and journalctl, which may occasionally leak sensitive parameters or tokens passed on command lines.

If shadow group passwords (/etc/gshadow) are used with newgrp, ensure /etc/gshadow maintains strict 0640 (root:shadow) or 0000 permissions so unprivileged users cannot extract group password hashes.

GNU/Linux, BSD, and BusyBox Implementation Differences

The groups and id utilities are part of POSIX and GNU coreutils, making them available on every Linux distribution, BSD variant, macOS, and BusyBox container. However, GNU groups username outputs username : group1 group2, whereas FreeBSD, macOS, and BusyBox groups username output group1 group2 without the username : prefix. Always use id -nG username in cross-platform scripts.

To list all system groups on macOS, getent group is unavailable; use dscl . list /Groups or dscacheutil -q group instead.

Troubleshooting Common Errors and Diagnostics

groups and groups $USER show different outputs in the same terminal

Root Cause: groups (no arguments) reads the group credentials cached in kernel memory for your current login session, whereas groups $USER queries /etc/group on disk.

Resolution: Log out and log back in (or run newgrp groupname / su - $USER) so your interactive shell reloads the updated group list from /etc/group.

groups
groups "$USER"
exec su -l "$USER"

A user can access group-owned files, but they are not listed in /etc/group

Root Cause: The group is assigned as the user's primary group (field 4 of /etc/passwd) rather than a supplementary group in /etc/group.

Resolution: Run id username or inspect the fourth field of getent passwd username to see their primary GID.

id username
getent passwd username | cut -d: -f1,4

groups: 'username': no such user

Root Cause: The specified username does not exist in /etc/passwd or any active NSS directory service.

Resolution: Verify the exact spelling of the username with getent passwd | grep -i partialname.

getent passwd | cut -d: -f1 | grep -i "alex"

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Run getent group to list all local and network groups along with their GIDs and members, or run getent group | cut -d: -f1 to print only the group names.
Running groups without arguments prints the groups loaded in your current shell process's memory at login time. Running groups username queries /etc/group on disk. If an admin recently added you to a group with usermod -aG, it will show in groups username immediately, but only in bare groups after you log out and back in.
Run getent group groupname to see the supplementary members in the fourth colon-separated field, and also check getent passwd | awk -F: '$4 == GID {print $1}' for any user whose primary group is set to that GID.
groups only prints human-readable group names, whereas id prints the numeric UID, primary GID, and all supplementary GIDs alongside their names (and supports flags like id -nG and id -u for clean scripting).
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout