Coder Perfect

How can I get a list of all the members of a Linux group?


In Linux (and possibly other operating systems), how can I get a list of all members of a group?

Asked by user323094

Solution #1

getent group <groupname>;

It works with local group/password files, NIS, and LDAP setups and is portable between Linux and Solaris.

Answered by Josh H

Solution #2

I’m afraid there isn’t a good, portable technique to achieve this that I’m aware of. Users who have that group as their primary group and anyone who has been added to that group using a mechanism other than UNIX flat files will be missed if you try to parse /etc/group as others have suggested (i.e. LDAP, NIS, pam-pgsql, etc.).

If I absolutely had to do this myself, I’d probably do it in reverse: use id to get the groups of every user on the system (which will pull all sources visible to NSS), and use Perl or something similar to maintain a hash table for each group discovered noting the membership of that user.

I can get a list from both flat files and LDAP, however that may or may not be true in your environment.

Edit 2: Someone mentioned to me that getent passwd will return a list of all users on the system, including those through LDAP/NIS/etc., but getent group will still miss people who are only members via the default group entry, so I wrote this simple hack.

#!/usr/bin/perl -T
# Lists members of all groups, or optionally just the group
# specified on the command line
# Copyright © 2010-2013 by Zed Pobre ( or
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.

use strict; use warnings;

$ENV{"PATH"} = "/usr/bin:/bin";

my $wantedgroup = shift;

my %groupmembers;
my $usertext = `getent passwd`;

my @users = $usertext =~ /^([a-zA-Z0-9_-]+):/gm;

foreach my $userid (@users)
    my $usergrouptext = `id -Gn $userid`;
    my @grouplist = split(' ',$usergrouptext);

    foreach my $group (@grouplist)
        $groupmembers{$group}->{$userid} = 1;

    foreach my $group (sort keys %groupmembers)
        print "Group ",$group," has the following members:\n";
        print "\n";

sub print_group_members
    my ($group) = @_;
    return unless $group;

    foreach my $member (sort keys %{$groupmembers{$group}})
        print $member,"\n";

Answered by Zed

Solution #3

To get a list of group members, use Python:


Answered by Narayanaperumal Gurusamy

Solution #4

lid -g groupname | cut -f1 -d'(' 

Answered by Memo

Solution #5

The following command will list all users belonging to , but only those managed by /etc/group database, not LDAP, NIS, etc. It also works for secondary groups only, it won’t list users who have that group set as primary since the primary group is stored as GID (numeric group ID) in the file /etc/passwd.

grep <your_group_name> /etc/group

Answered by Jose Bagatelli

Post is based on