How can I add an existing user to an existing group id (not group name)?

Solution 1:

So this turns out to be an XY problem

  1. problem as stated (X) "How to add existing user to existing group id (not group name)?"

  2. actual problem (Y) "What should I do if the /etc/group and /etc/gshadow files disagree about a group's numeric GID?"


X. How to add existing user to existing group id (not group name)?

It's not explicit in the man page, but usermod will accept a numeric GID as an argument for both the -g (primary group) and -G (secondary groups) options, at least as tested on Ubuntu 18.04.

Ex. given

$ groups testuser
testuser : testuser staff

$ getent group ftp
ftp:x:134:

then

$ sudo usermod -aG 134 testuser

$ groups testuser
testuser : testuser staff ftp

Y. What should I do if the /etc/group and /etc/gshadow files disagree about a group's numeric GID?

There's a command-line tool for that, provided as part of the passwd package:

NAME
       grpck - verify integrity of group files

SYNOPSIS
       grpck [options] [group [ shadow ]]

DESCRIPTION
       The grpck command verifies the integrity of the groups information. It
       checks that all entries in /etc/group and /etc/gshadow have the proper
       format and contain valid data. The user is prompted to delete entries
       that are improperly formatted or which have other uncorrectable errors.

       Checks are made to verify that each entry has:

       ·   the correct number of fields

       ·   a unique and valid group name

       ·   a valid group identifier (/etc/group only)

       ·   a valid list of members and administrators

       ·   a corresponding entry in the /etc/gshadow file (respectively
           /etc/group for the gshadow checks)

To check for inconsistencies, first run in read-only mode:

sudo grpck -r

(elevated privileges are required even here because /etc/gshadow is only readable by root). Then once you have identified the problem, run again interactively to correct problems:

sudo grpck

There is analogous utility pwck for ensuring consistency between /etc/passwd and /etc/shadow.

Solution 2:

TL;DR to answer the title question, please follow @steeldriver post aka. usermod works with group ID as well. The solution below is specifically for the problem described in the body of the OP.

Apparently the problem is resolved by editing /etc/group and change the docker group id 131 to 999. After logging out and in again I only have one group of docker left - the 999 group.

$ id foo
uid=305800(foo) gid=5000(student) groups=27(sudo),999(docker)

I very much hope changing /etc/group will not lead to any weird behaviour. The root of the problem is still unknown (the server login is also managed under a LDAP system so perhaps the two interferes each other).