How to list all users in a Linux group?

后端 未结 20 1212
春和景丽
春和景丽 2020-12-07 06:51

How do I list all members of a group in Linux (and possibly other unices)?

20条回答
  •  Happy的楠姐
    2020-12-07 07:45

    The following shell script will iterate through all users and print only those user names which belong to a given group:

    #!/usr/bin/env bash
    getent passwd | while IFS=: read name trash
    do
        groups $name 2>/dev/null | cut -f2 -d: | grep -i -q -w "$1" && echo $name
    done
    true
    

    Usage example:

    ./script 'DOMAIN+Group Name'
    

    Note: This solution will check NIS and LDAP for users and groups (not only passwd and group files). It will also take into account users not added to a group but having group set as primary group.

    Edit: Added fix for rare scenario where user does not belong to group with the same name.

    Edit: written in the form of a shell script; added true to exit with 0 status as suggested by @Max Chernyak aka hakunin; discarded stderr in order to skip those occasional groups: cannot find name for group ID xxxxxx.

提交回复
热议问题