How to get a list of usernames assigned to a group in FreeBSD 11.1?

This Question asks for a list of users or a list of groups.

This Question asks for users who happen to be members of multiple specific groups.

➥ But how to ask simply for a list of users currently assigned to a single specific group, such wheel?

I prefer a solution in a single command if possible. But if not feasible, a script would be useful and educational.

  • Is a moderately complicated script parsing /etc/passwd and /etc/groups OK, or do you want a system command? – Law29 Dec 2 '18 at 21:52
  • @Law29 Either, or both. I added note in Question. – Basil Bourque Dec 2 '18 at 21:57
  • 2
    Why not just getent group groupname? – Nasir Riley Dec 2 '18 at 22:02
  • @NasirRiley Can you show example? – Basil Bourque Dec 2 '18 at 22:03
  • @BasilBourque It's just like I typed it. Replace groupname with the group that you want. – Nasir Riley Dec 2 '18 at 22:12

You can select users with specific group from list of all users given by pw utility:

pw usershow -P -a | grep groupname

Result will be something like:

Login Name: username1     #1024         Group: groupname          #1002
Login Name: username2     #1025         Group: groupname          #1002
  • 1
    This is useful because it indicates the pw utility. No idea why it was downvoted (and my three-month-old answer got just downvoted too). – Law29 Mar 21 '19 at 16:51

Disregarding system scripts like getent, users can be in a group in two ways: either it is their principal group, defined in /etc/passwd, or they have it as a secondary group in /etc/groups.

sed -rn "s/^[^:]*:[^:]*:$GROUPID://p" < /etc/group | tr ',' '\n'
sed -rn "s/^([^:]*):[^:]*:[^:]*:$GROUPID:.*/\\1/p" < /etc/passwd

Should do it nicely. awk would probably look nicer...

awk -F: -v "g=$GROUPID" '{if ($3==g) print $1;}' /etc/passwd
awk -F: -v "g=$GROUPID" '{if ($3==g) print $4;}' /etc/group | tr ',' '\n'

https://www.cyberciti.biz/faq/linux-list-all-members-of-a-group/ thread show multiple ways of doing this. I personally prefer members method. but the method below is native and works well.

$ grep 'grpup-name-here' /etc/group
$ grep 'ftponly' /etc/group
$ grep -i --color 'ftponly' /etc/group

The proper way to show all users in a certain group under FreeBSD is:

# pw groupshow groupname

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.