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,dq:x:10030:b,c,f,gr:x:10031:a,b,c,es:x:10032:c,gt:x:10033:a,b,c,d,eso how to achieve this ?
adding list of users to multiple groups
shell script;users;group
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 doneNOTE: The above assumes a bash version >= 4 since associative arrays were not available in earlier versions. 