Delete non-unique group with group ID as primary group of a user

group

So say I have two groups with names testing1 and testing2. Both groups have the same group ID of 2000. Then I add a user named testing-user with GID of 2000. Along the way I want to delete group testing2, but I cannot because when I try I get the following response

groupdel: cannot remove the primary group of user 'testing-user'

Here are the methods I have tried around this to success:

  • Modified testing1's GID and then deleted testing2, then changed testing1's GID back to 2000

  • Modified testing-user's primary GID to a separate group, deleted testing2 then assigned testing-user to testing1

Is there a better method for this that does not involve modifying the users or group id's in question?

Best Answer

The error you're getting is a limitation of the way groupdel was written and the fact that the system is designed around numbers (IDs) and not names. As you can see in source code of groupdel, it only checks if there's a user having the GID you want to delete, as its primary group. It doesn't matter if there's another group having the same ID, but named differently.

/* [ Note: I changed the style of the source code for brevity purposes. ]
 * group_busy - check if this is any user's primary group
 *
 *      group_busy verifies that this group is not the primary group
 *      for any user.  You must remove all users before you remove
 *      the group.
 */
static void group_busy (gid_t gid)
{
        struct passwd *pwd;

        /* Nice slow linear search. */
        setpwent ();
        while ( ((pwd = getpwent ()) != NULL) && (pwd->pw_gid != gid) )
                ;
        endpwent ();

        /* If pwd isn't NULL, it stopped because the gid's matched. */
        if (pwd == (struct passwd *) 0)
                return;

        /* Can't remove the group. */
        fprintf (stderr,
                 _("%s: cannot remove the primary group of user '%s'\n"),
                 Prog, pwd->pw_name);
        exit (E_GROUP_BUSY);
}

So you either you mess with the configuration files using other tools like Perl in mtm's answer or you temporarily change the GID of that user so that group_busy doesn't fail anymore.

Related Question