I am creating a bash script which creates a user and sets a password. When the command "passwd user" is run it requires the user to enter a password and stops my script.

Is there any way to fulfill user input without having the user intervene?


yum -y update
adduser test-user
passwd test-user
"Password here?"
  • Isn't useradd available on Fedora or CentOS or whatever your RPM-based distribution is? – terdon Nov 19 '14 at 16:56

Method #1 - using passwd

You can do something like this via a script:

echo -n "$passwd" | passwd "$uname" --stdin

Where the password you want to set is $passwd and the user you want to set it for is $uname.

Method #2 - using useradd

You could also provide it to useradd directly:

useradd -n -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"

NOTE: Assuming you're on a Red Hat based distro such as CentOS or RHEL in method #2, since you're example shows yum commands. The -n switch, for example, is in older versions of useradd:

-n  A group having the same name as the user being added to the system 
    will be created by default. This option will turn off this
    Red Hat Linux specific behavior. When this option is used, users by 
    default will be placed in whatever group is specified in
    /etc/default/useradd. If no default group is defined, group 1 will be

newer versions of useradd now have the option this way on Red Hat and non Red Hat distros:

-N, --no-user-group
    Do not create a group with the same name as the user, but add the 
    user to the group specified by the -g option or by the GROUP 
    variable in /etc/default/useradd.

So you could use this command for other distros:

useradd -N -M -s $shell -g $group -d "/home/$homedir" "$uname" -p "$passwd"
| improve this answer | |
  • I tried method #2 in Ubuntu Server and received the following. useradd -n -M -s /bin/bash -g test135 -d "/home/testing135" "testing135" -p "testing135" useradd: invalid option -- 'n'. Any ideas? – user3024130 Nov 19 '14 at 22:04
  • @user3024130 - How are you doing yum commands in your example if this is an Ubuntu system? the method I showed you was for RH based distros only given your example. – slm Nov 19 '14 at 22:33
  • @user3024130 - see updates. – slm Nov 19 '14 at 22:45

This is a really bad idea, but you can pass the password on standard input:

passwd --stdin test-user <<< "Password here?"
| improve this answer | |
  • I think you'll need to send the password twice. – muru Nov 19 '14 at 16:45
  • Nope. It's not like the interactive process. Just try it. – l0b0 Nov 19 '14 at 16:49
  • It's not an option on Ubuntu's passwd, so I can't. – muru Nov 19 '14 at 17:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.