Show all users and their groups/vice versa

Solution 1:

All users:

$ getent passwd

All groups:

$ getent group

All groups with a specific user:

$ getent group | grep username

Solution 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';
done

Solution 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

Output;

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

Solution 4:

List all users

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

Or

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

Or

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