4

The 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 $text

I was able to get the shell script to add the new user (I checked the /etc/passwd entry). 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.

2

2 Answers 2

4

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
8
  • On my host (Linux Mint) the --stdin does not work: passwd: unrecognized option '--stdin'
    – Lambert
    Dec 11, 2015 at 10:31
  • Alternative is to use read -rs newpassword; useradd -p $(md5pass "$newpassword") $username
    – Lambert
    Dec 11, 2015 at 10:43
  • The '--stdin' also does not work on my host. I tried the 'chpasswd' but that also does not seem to work. Any other advice
    – Tech Check
    Dec 11, 2015 at 10:57
  • which OS do you use?
    – Tem
    Dec 11, 2015 at 11:00
  • I use QEMU Linux.
    – Tech Check
    Dec 11, 2015 at 11:03
0
#!/bin/bash
echo "Enter username: "
read username
useradd "$username"
echo "temp4now" | passwd --stdin "$username"
chage -d 0 "$username"
1
  • 1
    A bit of explanation (esp. for lines -1 and -2) would be quite nice. Feb 10, 2017 at 9:25

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .