-1

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.

DazedNConfused
  • 189
  • 2
  • 13
  • 1
    Use https://www.shellcheck.net/ to check your syntax – Mat Sep 04 '18 at 07:09
  • 1
    You are missing a `fi` to start with. There are better ways of splitting those fields than by using external programs like `grep` and `cut`. What's `b4` all about? – cdarke Sep 04 '18 at 07:13
  • its supposed to be 4. thats a mistake. ty for the fi correction. – DazedNConfused Sep 04 '18 at 07:23
  • Also see [How to use Shellcheck](https://github.com/koalaman/shellcheck), [How to debug a bash script?](https://unix.stackexchange.com/q/155551/56041) (U&L.SE), [How to debug a bash script?](https://stackoverflow.com/q/951336/608639) (SO), [How to debug bash script?](https://askubuntu.com/q/21136) (AskU), [Debugging Bash scripts](http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_02_03.html), etc. – jww Sep 04 '18 at 08:15

1 Answers1

3

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
Barmar
  • 741,623
  • 53
  • 500
  • 612