74

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?

1
  • 1
    An answer to get groudid from group name from another community askubuntu.com/a/639998/1577458 which also presents a more explicit version (without short tags) in a comment getent group root | cut --delimiter ':' --fields 3)`
    – K. Bogdan
    Commented Mar 9, 2022 at 16:14

5 Answers 5

95
getent group 124
# mysql:x:124:

getent group mysql
# mysql:x:124:
0
34

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

6

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.

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

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

-10

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
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.