Changing Group Membership from a Shell Script


About this document
Sample code

About this document

This document describes a method of using a non-interactive script to change group membership and bypass group limits.

AIX includes two commands for changing group set membership. They are newgrp and setgroups. Both of these commands require that the user enter the command from the command line. These commands cannot be executed from a shell script.

The sample code in this document provides a way to set the real and effective group ID from a shell script. The tool verifies that the current user is a member of the target group before executing the named command.

This document applies to AIX Versions 3.2 and 4.

Sample code

NOTE: Page headers and footers may appear in the following code. They should be removed before the code is used. Also, revision bars (vertical bars in the left margin which mark changes in the document), may appear to the left of the code and should be removed before the code is used.

 * NAME: switchgrp 
 *   cc -o switchgrp switchgrp.c 
 *   chown root switchgrp 
 *   chmod 4555 switchgrp 
 *   mv switchgrp <local extensions directory> 
 *   Set real and effective group ID to a value from /etc/group. 
 *   switchgrp allows a user to bypass the 32-group limitation without 
 *   using the newgrp command.  newgrp cannot be used inside a shell 
 *   script because of how it works. 
#include <stdio.h> 
#include <pwd.h> 
#include <grp.h> 
#include <sys/id.h> 
main (int argc, char ** argv) 
    char      *newgrp = argv[1]; 
    struct    passwd  *pwd; 
    struct    group   *grp; 
    int       i; 
    if (argc < 3) { 
        fprintf (stderr, "usage: switchgrp group cmd [ args ] 
        exit (1); 
    if (! (grp = getgrnam (newgrp))) { 
        fprintf (stderr, "unknown group: %s 
", newgrp); 
        exit (1); 
    if (! (pwd = getpwuid (getuid ()))) { 
        fprintf (stderr, "who are you? 
        exit (1); 
    for (i = 0;grp->gr_mem[i];i++) 
        if (strcmp (pwd->pw_name, grp->gr_mem[i]) == 0) 
    if (grp->gr_mem[i] == (char *) 0) { 
        fprintf (stderr, "not a member 
        exit (1); 
    setgidx (ID_REAL|ID_EFFECTIVE, grp->gr_gid); 
    setuid (getuid ()); 
    execvp (argv[2], &argv[2]); 
    perror (argv[2]); 
    exit (255); 

[ Doc Ref: 90605223414644     Publish Date: Jan. 25, 2001     4FAX Ref: none ]