How to list all users in a Linux group?

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

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

20条回答
  •  死守一世寂寞
    2020-12-07 07:47

    Here is a script which returns a list of users from /etc/passwd and /etc/group it doesn't check NIS or LDAP, but it does show users who have the group as their default group Tested on Debian 4.7 and solaris 9

    #!/bin/bash
    
    MYGROUP="user"
    
    # get the group ID
    MYGID=`grep $MYGROUP /etc/group | cut -d ":" -f3`
    if [[ $MYGID != "" ]]
    then
      # get a newline-separated list of users from /etc/group 
      MYUSERS=`grep $MYGROUP /etc/group | cut -d ":" -f4| tr "," "\n"`
      # add a newline
      MYUSERS=$MYUSERS$'\n'
      # add the users whose default group is MYGROUP from /etc/passwod 
      MYUSERS=$MYUSERS`cat /etc/passwd |grep $MYGID | cut -d ":" -f1`
    
      #print the result as a newline-separated list with no duplicates (ready to pass into a bash FOR loop)
      printf '%s\n' $MYUSERS  | sort | uniq
    fi
    

    or as a one-liner you can cut and paste straight from here (change the group name in the first variable)

    MYGROUP="user";MYGID=`grep $MYGROUP /etc/group | cut -d ":" -f3`;printf '%s\n' `grep $MYGROUP /etc/group | cut -d ":" -f4| tr "," "\n"`$'\n'`cat /etc/passwd |grep $MYGID | cut -d ":" -f1`  | sort | uniq
    

提交回复
热议问题