How do I list all members of a group in Linux (and possibly other unices)?
Use Python to list groupmembers:
python -c "import grp; print grp.getgrnam('GROUP_NAME')[3]"
See https://docs.python.org/2/library/grp.html
just a little grep and tr:
$ grep ^$GROUP /etc/group | grep -o '[^:]*$' | tr ',' '\n'
user1
user2
user3
You can do it in a single command line:
cut -d: -f1,4 /etc/passwd | grep $(getent group <groupname> | cut -d: -f3) | cut -d: -f1
Above command lists all the users having groupname as their primary group
If you also want to list the users having groupname as their secondary group, use following command
getent group <groupname> | cut -d: -f4 | tr ',' '\n'
Here's another Python one-liner that takes into account the user's default group membership (from /etc/passwd
)as well as from the group database (/etc/group
)
python -c "import grp,pwd; print set(grp.getgrnam('mysupercoolgroup')[3]).union([u[0] for u in pwd.getpwall() if u.pw_gid == grp.getgrnam('mysupercoolgroup')[2]])"
The following command will list all users belonging to <your_group_name>
, 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
I have tried grep 'sample-group-name' /etc/group
,that will list all the member of the group you specified based on the example here