adding list of users to multiple groups

I want to write a shell script which will add list of users, defined in users.txt, to multiple existing groups.

For example, I have a, b, c, d, e, f, g users which will be added to the groups according to script, and I have p, q, r, s, t groups. Below is the expected output of /etc/groups file :


so how to achieve this ?


The best and simplest approach would be to parse a file with the required information as suggested by @DannyG. While that’s the way I would do it myself, another would be to hardcode the user/groups combinations in your script. For example:

#!/usr/bin/env bash

## Set up an indexed array where the user is the key
## and the groups the values.
declare -A groups=(

## Now, go through each user (key) of the array,
## create the user and add them to the right groups.
for user in "${!groups[@]}"; do 
    useradd -U -G "${groups[$user]}" "$user" 

NOTE: The above assumes a bash version >= 4 since associative arrays were not available in earlier versions.

Leave a Reply

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