简体   繁体   中英

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?

getent group 124
# mysql:x:124:

getent group mysql
# mysql:x:124:

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('carmenes').gr_gid)"

这使用来自https://man7.org/linux/man-pages/man3/getgrnam.3.htmlgetgrnam

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM