0

I am now trying to create users in Ubuntu from a text file and it looks like this:

student1
student2
student3
student4
student5

However, I keep getting invalid user name error. For instance 'seradd: invalid user name 'student5

Here is my code. The first argument is input file and the second input is output file. Can anyone help?

#!/bin/bash
if test ${#} -lt 1 
then
    echo "Please provide the input file"
    exit 1
else
    cat ${1} | while read user
    do
        randompw=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)
        useradd -m -s /bin/bash ${user}
        echo ${newuser}:${randompw} | chpasswd
        if test $# -lt 2
            then
                echo ${newuser}:${randompw} >> pwlist.txt
            else
                echo ${newuser}:${randompw} >> ${2}
            fi
        if id -u ${user}
            then
                echo "User account ${user} created successfully"
            else
                echo "User account ${user} created unsuccessfully"
            fi
    done
fi
SamFH
  • 31
  • 2

1 Answers1

0

The variable newuser is not defined. I think you meant $user instead.

Suggestion:

  • Enclose variable references and computations within double quotes. I fixed that.
#!/bin/bash
if test ${#} -lt 1
then
    echo "Please provide the input file"
    exit 1
else
    cat "${1}" | while read user
    do
        randompw="$(cat /dev/urandom | tr -dc 'a-zA-Z0-9' | fold -w 8 | head -n 1)"
        useradd -m -s /bin/bash "${user}"
        echo "${user}:${randompw}" | chpasswd
        if test $# -lt 2
            then
                echo "${user}:${randompw}" >> pwlist.txt
            else
                echo "${user}:${randompw}" >> ${2}
            fi
        if id -u "${user}"
            then
                echo "User account ${user} created successfully"
            else
                echo "User account ${user} created unsuccessfully"
            fi
    done
fi
Mike Slinn
  • 7,705
  • 5
  • 51
  • 85
  • Thanks. However, I have edited the code according to your fixed one and it's still giving the same error – SamFH Apr 17 '21 at 15:29
  • `'seradd: invalid user name 'student1 ) pam_chauthtok() failed, error: Authentication token manipulation error ) password not changedr student1 id: 'student1\r': no such user – SamFH Apr 17 '21 at 15:33