Search:  
Gentoo Wiki

TIP_Adding_many_users_to_a_group

This article is part of the Tips & Tricks series.
Terminals / Shells Network X Window System Portage System Filesystems Kernel Other

Unless I am mistaken, in unix, there is no 'standard' easy way to add a bunch of users to the same group. Yes, you can find graphical tools to do it, but it would be nice just to have a small script in your bag of tricks too, don't you think?

Here is one:

Code: adduserstogroup

 #!/bin/bash
 # adduserstogroup  -- adds a bunch of users to a single group.
 # Ten-minute hack by Michael Lockhart, michael.lockhart@tpg.com.au
 # for use by sysadmin.
 #
 #  usage:  adduserstogroup grp usr1 usr2 ... usrn
 #  will add usr1...usrn to group grp
 #
 # AUTHORS:  Michael Lockhart  (MJL)
 #           Thomas Margreiter (T M)
 #
 # Version:  0.2
 #
 # Copyright 2005, Michael Lockhart.  You may use, copy, modify and distribute
 # this script under the terms of the GPL, ver. 2.0.  For details of the
 # GPL, please visit http://www.fsf.org/licensing
 #
 # NO WARRANTY.  This script is provided "as is" with no warranty.  If it
 # breaks your system, you get to keep all of the pieces.
 #
 # HISTORY
 #
 # MJL20050702 - Created.
 # MJL20050704 - Added a check that the group actually exists.
 # T M20051124 - Changed the script for working with RedHat Releases
 #
 
 if [ $# -ge 2 ]; then
   if [ $UID == 0 ]; then
     egrep ^$1 /etc/group > /dev/null
     if [ $? == 0 ]; then
       GROUPNAME=$1
       shift
       while [ $# -gt 0 ]; do
         CURRENT=$1
         echo $GROUPNAME `groups $CURRENT` |sed 's/.*: //g' | sed 's/ /,/g' | usermod -G `cat -`,$GROUPNAME $CURRENT
         shift
       done
     else
       echo "the group $1 does not exist."
     fi
   else
     echo "you must be ROOT to run this script."
   fi
 else 
   echo "usage:  $0 grp usr1 [usr2 ... usrN]"
 fi
 

Now you can add a bunch of users to a single group. This might be handy, say, when you add a new group to control a device or system service (cdrom, or ppp come to mind...). For example, this is how you would create a group called "ppp" and add existing users to it:

 # groupadd ppp
 # adduserstogroup ppp mjl jen esr bob joe

Enjoy...

Retrieved from "http://www.gentoo-wiki.info/TIP_Adding_many_users_to_a_group"

Last modified: Fri, 05 Sep 2008 23:20:00 +0000 Hits: 17,203