Kedar Joshi
Kedar Joshi

Reputation: 1462

Linux: How to get group id from group name? and vice versa?

I want to retrieve group id of a particular group name. Is there a command in Linux/UNIX systems to do this? Also if I want to do it the other way - get group name from group id, is that also possible?

Upvotes: 70

Views: 117659

Answers (5)

python -c "import grp; print(grp.getgrnam('groupname').gr_gid)"

This uses getgrnam from https://man7.org/linux/man-pages/man3/getgrnam.3.html.

Upvotes: 2

kberg
kberg

Reputation: 2379

getent group 124
# mysql:x:124:

getent group mysql
# mysql:x:124:

Upvotes: 86

david.perez
david.perez

Reputation: 7012

Given the gid, here is how to get the group name:

getent group GID | cut -d: -f1

Given the group name, we get the gid:

getent group groupname | cut -d: -f3

UPDATE:

Instead of cut a bash builtin can be used: Example, get the group name for group ID 123.

groupid=123 IFS=: read GROUP_NAME REST <<<`getent group $groupid` echo $GROUP_NAME

Upvotes: 34

ADM-IT
ADM-IT

Reputation: 4180

You can use the following command:

awk -F\: '{print "Group " $1 " with GID=" $3}' /etc/group | grep "group-name"

or

cat /etc/group | grep group-name

where group-name is your group to search.

Upvotes: 5

Dixel
Dixel

Reputation: 564

I saw here that you can use the id command to get gid or uid from group name or username respectively.

id -u username

and

id -g groupname

Upvotes: -8

Related Questions