Skip to content
Advertisement

Bash/xargs: How to mass assign user privileges?

I have created a new user. My current user obviously has the following rights:

$ groups
max adm cdrom sudo dip plugdev lpadmin lxd sambashare

Where max is the name of the current user account.

I tried paramer expansion but the output of ${groups} is empty, so I just piped groups to xargs

$ groups | xargs -I _ sudo usermod -aG _ new_user_name

I get the error message that there is no folder max adm cdrom sudo dip plugdev lpadmin lxd sambashare because obviously the output of groups is not splitted by whitespace.

But as I said ${groups} is empty, so there is nothing I could pipe to xargs.

Second try:

my_arr=(adm cdrom sudo dip plugdev lpadmin lxd sambashare)

$ echo ${my_arr[@]} | xargs -I _ usermod -aG _ new_user_name

The arguments of the array don’t get splitted even though I don’t put the parameter expansion in double quotes.

xargs treats the piped arguments still as one big string adm cdrom sudo dip plugdev lpadmin lxd sambashare

What’s the right solution?

Advertisement

Answer

usermod adds one or more users to one group at a time, so you’ll have to use a loop:

for g in "${my_arr[@]}"; do
  usermod -aG "$g" new_user_name
done

Note that xargs by default uses as many arguments as possible in one invocation of the supplied command, so if you go with xargs, limit the number of arguments consumed to one at a time (-n 1):

echo "${my_arr[@]}" | xargs -n 1 -I _ usermod -aG _ new_user_name
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement