Bash Shell Automatically Creating User - Adduser

I need to automatically create a user by reading lines of a file that contains username, home directory and full name.

I am new to bash shell scripting and it is very confusing to me.

There is something wrong with my adduser command. It gives the error - adduser: Only one or two names allowed.

following is the full script -

while read line;
do 
      fieldnumbers=$(echo $line | grep - o " " | wc - l)
      username=$(echo $line | cut -d' ' -f 1)
      home=$(echo $line | cut -d' ' -f 2)
      firstname=$(echo $line | cut -d' ' -f 3)

      if [[ "$fieldnumbers" -eq b4 ]]
      then
               middlename=""
      else
               middlename=$(echo $line | rev | cut -d' ' -f 2)

      lastname=$(echo $line | rev | cut -d' ' -f 1)
      password=$(echo pwgen 7 1) #create random password
      fullname="$firstname $middlename $lastname"

      echo "username is : $username"
      sudo adduser --gecos $fullname --disabled-password --home $home $username

      echo 'username:$password' | chpasswd
       echo "Password is for $username is: $password"
done < users.txt

I am sure that this script is riddled with syntax errors. Please help. my brain is fried.

4

1 Answer

Always quote your variables unless you deliberately want to split the value into separate words.

sudo adduser --gecos "$fullname" --disabled-password --home "$home" "$username"

Also, you have to use double quotes around strings containing variables, not single quotes, if you want the variables to be expanded.

Difference between single and double quotes in Bash

So this line:

echo 'username:$password' | chpasswd

should be:

echo "username:$password" | chpasswd
3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

James H. Sterling

James H. Sterling

Environmental Science & Climate Journalist

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.

Share this article
Twitter Facebook Pinterest