0

I have a username.txt file which contains their username and specific group. As of right now I'm trying to create a bash script which allows me to create an account for each user and add the user to its group in one command.

This is currently my failed bash script:

#!/bin/bash

sudo addgroup staff
sudo addgroup visitors

username="username.txt"

while read line; do
sudo useradd $-Eo '^[^,]+' $username;
if [grep staff $username]; then
  sudo usermod -a -G staff
else
  sudo usermod -a -G visitors
done < $username

This is what is inside my username.txt file:

ellipsiscoterie,visitor
magnetcommonest,visitor
belateddefensive,staff
bobstercaramelize,staff
0

Please try this as a solution. You are using a comma-separated file so my assumption is that you want to use more than two groups at one point. What you are doing is not completely wrong, but I would avoid using if else in this case as it will need a rewrite in case more groups will be needed. The creation of the group is handled within the loop as well.

#!/bin/bash
while read config
do
        USERTOCREATE=$(awk -F, '{print $1}' <(echo "$config"))
        GROUPTOASSIGN=$(awk -F, '{print $2}' <(echo "$config"))
        if [[ ! $(groups) =~ $GROUPTOCREATE ]]; then addgroup $GROUPTOASSIGN; fi
        useradd $USERTOCREATE
        usermod -a -G $GROUPTOASSIGN
done < users

This code is a simple while loop that uses two variables USERTOCREATE and GROUPTOASSIGN which are assigned using the awk. -F, flag in awk is to set a field separator FS variable to comma. This way awk can split input into variables $1 and $2. I'm not sure if you are familiar with <() this is a file descriptor that allows us to treat the output of echo "$config" as a file. $config is nothing else than the line coming from the file the script is reading.

| improve this answer | |
0
#!/bin/bash
i=0

n=$(wc -l <username.txt)
while [ $i -le $n ]
do
        L=$(awk "NR==$i" username.txt)
        if [ -n "$L" ]; then
                user=$(echo "$L" | cut -d',' -f1)
                group=$(echo "$L" | cut -d',' -f2)
                useradd $user
                groupadd $group
                usermod -a -G $group $user
        fi

i=$((i+1))
done
| improve this answer | |
0

You could parse the username.txt line-wise, with , as field separator:

#!/bin/bash
sudo addgroup staff
sudo addgroup visitors

while IFS=, read -r username maingroup
do
   sudo adduser --ingroup "$maingroup" "$username"
done < username.txt

This would read the comma-separated tokens into the shell variables $username and $maingroup, respectively, and execute the adduser command to create the user $username with primary group $maingroup.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.