adding list of users to multiple groups Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of adding list of users to multiple groups without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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 :

p:x:10029:a,c,d
q:x:10030:b,c,f,g
r:x:10031:a,b,c,e
s:x:10032:c,g
t:x:10033:a,b,c,d,e

so how to achieve this ?

Answer

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=(
    ["alice"]="groupA,groupB" 
    ["bob"]="groupA,groupC" 
    ["cathy"]="groupB,groupD"
)

## 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" 
done

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

We are here to answer your question about adding list of users to multiple groups - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji