Devido aos seus comentários, você pode simplesmente criar estaticamente o script com os grupos escritos nele. Este script espera uma lista de usuários, um usuário por linha, na entrada padrão. Então, chame-o com ./script < users.txt
, por exemplo.
#!/bin/bash
groups="p q r" # the list of all groups you want your users in
# the following function is a case statement
# it takes as first argument a user, and as second argument a group
# it returns 0 if the user must be added to the group and 1 otherwise
must_belong_to() {
case $2 in # first we explore all the groups
p)
case $1 in # and for each of them, we examine the users
a | b ) # first selection: the users that must belong to the group
true
;;
*) # second selection: all the others
false
;;
esac
q)
# same here...
;;
esac
}
# we loop on the input file, to process one entry
# (i.e. one user) at a time
while read user
do
# We add the user. You may want to give some options here
# like home directory (-d), password (-p)...
useradd $user
# then we loop on the existing groups to see in which
# one the user must be added
for g in $groups
do
# if the user must be added to the group $g
if must_belong_to $user $g
then
# we add it with the command gpasswd
gpasswd -a $user $g
fi
done
done
Como explicado por @terdon, esta versão do must_belong_to()
pode crescer rapidamente. Aqui está outra solução usando matrizes associativas:
#!/bin/bash
declare -A groups
# we declare all the groups and then, for each one, its members
all_the_groups="a b"
groups[a]="p q r"
groups[b]="q r s"
must_belong_to() {
# we extract a list of all users for the group in parameter
read -a all_the_users <<< "${groups["$2"]}"
# we iterate over the users from the group
for u in $all_the_users
do
# if the user belong to the group,
# we return here
[[ $u == $1 ]] && return 0
done
# in case the user dosn't belong to the group,
# we end up here
return 1
}