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?
5 Answers
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
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.
python -c "import grp; print(grp.getgrnam('groupname').gr_gid)"
This uses getgrnam
from
https://man7.org/linux/man-pages/man3/getgrnam.3.html.
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
-
12man page for
id
says last argument is username, soid -g foo
will display the name of the main group for user "foo".– CDuvCommented Mar 15, 2019 at 19:57 -
explainshell.com/explain?cmd=id+-G+-g+-u Commented May 20, 2022 at 14:28
getent group root | cut --delimiter ':' --fields 3
)`