Reputation: 83
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
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-
#!/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
useradd
command to create the new user and assign it to an existing group.chpasswd
. If you're wondering why wrap those variable expansions with double quotes, check this answer out .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