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

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

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'

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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