List ALL users in a Unix Group (Primary and Secondary)

Is there a command or better combination of cmds that will give me the list of Unix users in a particular Unix group whether their primary group is that group in question (information stored in /etc/passwd) or they are in a secondary group (information stored in /etc/group).

So far all I got is a combination of the following:
groupName=XXXXX
groupId=$( getent group | egrep "^${groupName}:" | cut -d: -f3 )
getent passwd | egrep "^.*:.*:.*:${groupId}" | cut -f1 -d:
getent group | egrep "^${groupName}:" | cut -f4 -d:

(Yeah for all you NIS and/or LDAP guys, I did use the getent commands) :slight_smile:

hmm.
Some systems have a listgroup command - did you check yours for that command?

if you have Python, an alternative

#!/usr/bin/env python
d={}
for line in open("/etc/group"):
    line=line.strip().split(":")
    users=line[3]
    if users:
        for u in users.split(","):
            d.setdefault(u,[])
            d.append(line[0])
for i,j in d.iteritems():
    print "%s is in groups: %s" %(i,j)        

output

# ./test.py
daemon is in groups: ['bin']
user5 is in groups: ['dialout', 'video']
user2 is in groups: ['dialout', 'video']
user3 is in groups: ['dialout', 'video']
user1 is in groups: ['dialout', 'video']
nobody is in groups: ['nogroup']

If you have the "logins" command:

logins -g <group name>

groupName="$1"

# Save some processing, no need to call getent so much.
#
groupEntry=$(getent group | grep "^${groupName}:")
if [ ! "$groupEntry" ]; then
        echo "Group $groupName does not exist." >&2
        exit 1
fi

# Note it IS possible that the same group is found in a local /etc/group
# as well as another source, you'll get two results.  We'll assume the
# first one wins.
#
groupId=$(echo "$groupEntry" | cut -d: -f3 | head -1)

# A username could be in a primary group and have that SAME primary
# group redundantly set as a secondary group.
#
passwdUser=$(getent passwd | cut -d: -f1,4 | grep ":${groupdId}$" | cut -d: -f1)
echo "${groupEntry},${passwdUser}" | cut -d: -f4 | tr ',' '\012' | sed '/^$/d' | sort -u

Thanks everyone, the operating system is Solaris and the "logins -g <grp>" command works BEAUTIFULLY and provides some visibility on primary vs secondary groups, like the following:

logins -g unixGrpName
myadm 10000 myadm 10000
myserv 10200 myserv 10200
dbadm 10300 myadm 10000
Cuser1 47001 unixGrpName 47000 GECOS for CUser1
CUser2 47002 unixGrpName 47000 GECOS for CUser2
CUser3 47003 unixGrpName 47000 GECOS for CUser3

Kudos to Methyl!