All HowTo's Cyber-Security

A script to copy a user’s group membership in Bash

This is a very simple script to copy an existing user’s group membership to a new user. The new user will have thew same group membership as the original (copied) user. This is useful when a new employee comes along replacing an existing user and you (the sysadmin) are asked to use the existing user as a template for the new employee. This same script could also modify an existing user to have the appropriate group membership by replacing “useradd” with “usermod”.

Create the following script and call it anything you like. I used “”.


# AGIX - Andrew Galdes

if test "$#" -ne 2; then
        THIS=`basename "$0"`
        echo "Usage: ./${THIS} olduser newuser"

# Store the users in variables

# Get the list of groups into a variable
G=`groups ${OLDUSER} | cut -f2 -d':'`

# Clean it
G=`echo ${G} | sed 's/ /,/g'`

# Create the user with the right groups
useradd -G ${G} ${NEWUSER}

Run it like this where sally is the original user being copied and ben is the new user that doesn’t exist yet.

./ sally ben

Leave a Reply

Your email address will not be published. Required fields are marked *