What is the group id of this group name?

126,559

Solution 1

A hack for the needed: (still maybe there is much better answer)

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

Simpler version(Thanks to @A.B):

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

Example:

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

Solution 2

Use the getent command for processing groups and user information, instead of manually reading /etc/passwd, /etc/groups etc. The system itself uses /etc/nsswitch.conf to decide where it gets its information from, and settings in the files may be overridden by other sources. getent obeys this configuration. getent prints data, no matter the source, in the same format as the files, so you can then parse the output the same way you would parse /etc/passwd:

getent group sudo | awk -F: '{printf "Group %s with GID=%d\n", $1, $3}'

Note that, for a username, this much more easier. Use id:

$ id -u lightdm
105

Solution 3

This can be simply done with cut:

$ cut -d: -f3 < <(getent group sudo)
27

getent group sudo will get the line regarding sudo group from /etc/group file :

$ getent group sudo
sudo:x:27:foobar

Then we can just take the third field delimited by :.

If you want the output string accordingly, use command substitution within echo:

$ echo "Group sudo with GID="$(cut -d: -f3 < <(getent group sudo))""
Group sudo with GID=27
Share:
126,559

Related videos on Youtube

Maythux
Author by

Maythux

Love To Learn Love To Share

Updated on September 18, 2022

Comments

  • Maythux
    Maythux over 1 year

    How to get the group ID GID giving the group name.

    The output would be for example:

    Group adm with GID=4
    
  • A.B.
    A.B. almost 9 years
    Try this: awk -F\: '/sudo/ {print "Group " $1 " with GID=" $3}' /etc/group
  • A.B.
    A.B. almost 9 years
    Ok, awk is shorter than perl =)
  • muru
    muru almost 9 years
    Pretty sure perl can do the splitting for you, I think the -F or -l option does that.
  • A.B.
    A.B. almost 9 years
    % echo "Group cdrom with GID="$(cut -d: -f3 < <(getent group sudo))"" Group cdrom with GID=27, please a little more generic =)
  • kos
    kos almost 9 years
    Why the process substitution? What's wrong with GID="$(getent group cdrom | cut -d: -f3)"?
  • kos
    kos almost 9 years
    See UUOC
  • heemayl
    heemayl almost 9 years
    @kos I don't like running things in subshells unless is a must.....
  • heemayl
    heemayl almost 9 years
    @A.B. Edited...
  • kos
    kos almost 9 years
    But it's POSIX...:'( No, just joking, I genuinely didn't know the difference. +1
  • Zelphir Kaltstahl
    Zelphir Kaltstahl about 2 years
    Note, that this is Bash specific. Same result can be achieved with: getent group root | cut --delimiter ':' --fields 3 (or use short args). Seems like this case does not really require process substitution.