Matthew
Matthew

Reputation: 83

Useradd script in linux without using passwd

I have to write a useradd script which adds a new user and sets for him a home directory.

#!/bin/bash

echo "Name:"
read name
echo "Password:"
read password
echo "Group:"
read group
useradd -m -G $group -s /bin/bash -p $password $name

Everything works as intended but I have problems with the password in the following line -

useradd -m -G $group -s /bin/bash -p $password $name

It does not work so I need to use later in terminal passwd command.

How can I rebuild my script so I won't need to use passwd to setup password correctly? I have read that you can use stdin but I was not able to do this correctly.

Upvotes: 0

Views: 2288

Answers (1)

bijoy26
bijoy26

Reputation: 165

If you prefer to pipe the user's password from STDIN, use chpasswd utility which is quick and simple. as suggested by @Ardit.

This script should work for your purpose, assuming you meet the following conditions-

  • You are interacting as the root user
  • You have an existing group created for the purpose of your new user
#!/bin/bash

echo "Name:"
read name

echo "Password:"
read password

echo "Group:"   # group must exist
read group

# add new user, set group, create new home directory 
useradd -G $group -m $name           

# update new user password by piping from STDIN
echo ""$name":"$password"" | chpasswd           

# change the default user shell to bash 
chsh -s /bin/bash $name         
  1. First we execute useradd command to create the new user and assign it to an existing group.
  2. Then we pipe the name and password into chpasswd. If you're wondering why wrap those variable expansions with double quotes, check this answer out .
  3. Finally chsh utility is used to update the user shell.

Why not execute everything in a single statement?
I prefer subdividing a problem into smaller tasks for easier understanding.

Upvotes: 1

Related Questions