Scenario / Questions

I know I have existing groups and users but I’m not sure about their association. Is there an shell command I can use to list all users or all groups and a command to list all groups/users for a specified user/group?

So something like showusers would list all users, and showgroups -u thisuser would show all the groups that have thisuser in it.

Find below all possible solutions or suggestions for the above questions..

Suggestion: 1

All users:

$ getent passwd

All groups:

$ getent group

All groups with a specific user:

$ getent group | grep username

Suggestion: 2

List users and their groups:

for user in $(awk -F: '{print $1}' /etc/passwd); do groups $user; done

List groups and their users:

cat /etc/group | awk -F: '{print $1, $3, $4}' | while read group gid members; do
    members=$members,$(awk -F: "\$4 == $gid {print \",\" \$1}" /etc/passwd);
    echo "$group: $members" | sed 's/,,*/ /g';

Suggestion: 3

If you dont care about remote users such as LDAP or NIS,
to list users and their associated groups in a simple way:

cut -d: -f1 /etc/passwd | xargs groups


root : root
myuser : root www-data fuse 
anotheruser : anotheruser   cdrom floppy audio dip video plugdev scanner bluetooth netdev

Suggestion: 4

List all users

cut -d':' -f 1 /etc/passwd


awk -F ':' '{print $1}' /etc/passwd

While cat /etc/passwd shows all users (and a bunch of other stuff), cut -d ‘:’ -f 1 is a simple way to split each line with ‘:’ as a delimiter and extract just the first field (users). Pretty much the same as awk version.

List all groups

cut -d':' -f 1 /etc/group


awk -F ':' '{print $1}' /etc/group

Guess what, very simmilar to listing users. Just parse /etc/group instead.

Another interesting way, maybe closer to what OP wanted, is compgen. Not sure about compatibility issues though.

compgen -u
compgen -g

Suggestion: 5

Use getent passwd{1000..60000} to list only manually added users. See:

for user in $(getent passwd {1000..60000} |awk -F: '{print $1}');
    groups $user; 

Suggestion: 6

for debian

cat /etc/passwd # show all users
cat /etc/group # show all groups
cat /etc/passwd | grep group # show all users with specified group

Suggestion: 7

Like this:

sudo cat /etc/gshadow |grep group
sudo cat /etc/gshadow |grep username

Suggestion: 8

Use this command to get all the group and users in that particular group.

grep '
> ' /etc/group