Kevin Burke Kevin Burke - 1 year ago 61
Linux Question

Get a gid if you know the group name in Go

I created a group on a Linux machine. Now I am trying to call

to change a file's ownership to that new group.

requires me to know the
and the

func Chown(name string, uid, gid int) error

How can I get the
for my group? I tried using
, but I got "unknown user groupname"

I can call
, but this only returns me an array of group IDs - it doesn't tell me anything about the mapping between a group name and the group id.

I am guessing there is a Unix utility I can shell out to (parse the result of calling
) but I'd rather not do that if I can help it.

Answer Source

Update: As of August 16, 2016, Go 1.7 is released with support for LookupGroup. Upgrading to Go 1.7 is recommended if you want to access information about POSIX groups.

There is a LookupGroup function in the Go 1.7 betas, but it was added only this February and isn't in any released version of Go, so you're kind of out of luck.

As far as I can see your options are:

  1. Upgrade to a beta.
  2. Wait for the 1.7 release, scheduled for August.
  3. Write your own cgo function that calls getgrnam for the information you need (tricky)
  4. Write your own code that parses /etc/group (relatively easy... as long as you can guarantee that the info you need actually comes from that file and not LDAP or something).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download