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.
41 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
3ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJobGtpZmWDdYGOm5isoF2otaa4y2aYrqyfoq61tcKao6WxXZi%2Fpq3ToqWgZaWosrN5wJ2brquVpw%3D%3D