How to add users to Linux through a shell script
32,721
Output from "man 1 passwd":
--stdin
This option is used to indicate that passwd should read the new
password from standard input, which can be a pipe.
So to answer your question, use the following script:
echo -n "Enter the username: "
read username
echo -n "Enter the password: "
read -s password
adduser "$username"
echo "$password" | passwd "$username" --stdin
I used read -s for the password, so it won't be displayed while typing.
Edit: For Debian/Ubuntu users -stdin won't work. Instead of passwd use chpasswd:
echo $username:$password | chpasswd
Related videos on Youtube
Author by
Rastko Stamenkovic
Updated on September 18, 2022Comments
-
Rastko Stamenkovic 4 monthsThe shell script that I have to write has to create new users and automatically assign them to groups. This is my code so far:
echo -n "Enter the username: " read text useradd $textI was able to get the shell script to add the new user (I checked the
/etc/passwdentry). However, I have tried and I am not able to get a passwd (entered by the user) to the newly created user before. If anyone could help me assign a password to the newly created user it would be of much help.-
terdon about 7 yearsHave you triedman useradd? -
steve about 7 yearsAlso look at stackoverflow.com/questions/714915/… where use ofpasswd --stdinis covered.
-
-
Lambert about 7 yearsOn my host (Linux Mint) the--stdindoes not work:passwd: unrecognized option '--stdin' -
Lambert about 7 yearsAlternative is to useread -rs newpassword; useradd -p $(md5pass "$newpassword") $username -
Rastko Stamenkovic about 7 yearsThe '--stdin' also does not work on my host. I tried the 'chpasswd' but that also does not seem to work. Any other advice -
Tem about 7 yearswhich OS do you use?
-
Rastko Stamenkovic about 7 yearsI use QEMU Linux. -
Rastko Stamenkovic about 7 yearsWith the updated version it works. Instead of creating a new group with the name of the username, is there a way to assign the user to a specific already created group? -
Rastko Stamenkovic about 7 yearsI have resolved the issue by adding usermod -a -G "groupname" "username". This assigns the user to a secondary group. -
countermode almost 6 yearsA bit of explanation (esp. for lines -1 and -2) would be quite nice.