In Unix/Linux, how do you find out what group a given user is in via command line?
Asked
Active
Viewed 3.2e+01k times
283
-
25To get the opposite, see who is in a given group, you can use `getent group
`. – iconoclast Sep 27 '12 at 20:19 -
1@iconoclast : which doesn’t list users belonging to the group in /etc/passwd. – user2284570 Dec 13 '15 at 13:47
5 Answers
109
This one shows the user's uid as well as all the groups (with their gids) they belong to
id userid

Paul Tomblin
- 179,021
- 58
- 319
- 408
-
2This appears to be pretty useful as well. It has more verbose output than the 'groups' command, so if you need the group id/user id use this! – Alex Argo Dec 08 '08 at 17:02
-
This should be the most detailed and correct answer, have an upvote! – Harvey Lin Aug 14 '18 at 18:23
19
On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:
id -Gn [user]
which is equivalent to groups [user]
utility which has been obsoleted on Unix.
On OS X/Unix, the command id -p [user]
is suggested for normal interactive.
Explanation on the parameters:
-G
,--groups
- print all group IDs
-n
,--name
- print a name instead of a number, for-ugG
-p
- Make the output human-readable.
0
or just study /etc/groups (ok this does probably not work if it uses pam with ldap)

Nils
- 13,319
- 19
- 86
- 108
0
Below is the script which is integrated into ansible and generating dashboard in CSV format.
sh collection.sh
#!/bin/bash
HOSTNAME=`hostname -s`
for i in `cat /etc/passwd| grep -vE "nologin|shutd|hal|sync|root|false"|awk -F':' '{print$1}' | sed 's/[[:space:]]/,/g'`; do groups $i; done|sed s/\:/\,/g|tr -d ' '|sed -e "s/^/$HOSTNAME,/"> /tmp/"$HOSTNAME"_inventory.txt
sudo cat /etc/sudoers| grep -v "^#"|awk '{print $1}'|grep -v Defaults|sed '/^$/d;s/[[:blank:]]//g'>/tmp/"$HOSTNAME"_sudo.txt
paste -d , /tmp/"$HOSTNAME"_inventory.txt /tmp/"$HOSTNAME"_sudo.txt|sed 's/,[[:blank:]]*$//g' >/tmp/"$HOSTNAME"_inventory_users.txt
My output stored in below text files.
cat /tmp/ANSIBLENODE_sudo.txt
cat /tmp/ANSIBLENODE_inventory.txt
cat /tmp/ANSIBLENODE_inventory_users.txt

David Buck
- 3,752
- 35
- 31
- 35

Namasivayam Chinnapillai
- 297
- 1
- 5