Inputting user input automatically through bash script?
Solution 1
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
used.
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"
Solution 2
This is a really bad idea, but you can pass the password on standard input:
passwd --stdin test-user <<< "Password here?"
Related videos on Youtube
Hunter B
Updated on September 18, 2022Comments
-
Hunter B over 1 year
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?
#!/bin/bash yum -y update adduser test-user passwd test-user "Password here?"
-
terdon over 9 yearsIsn't
useradd
available on Fedora or CentOS or whatever your RPM-based distribution is?
-
-
muru over 9 yearsI think you'll need to send the password twice.
-
l0b0 over 9 yearsNope. It's not like the interactive process. Just try it.
-
muru over 9 yearsIt's not an option on Ubuntu's
passwd
, so I can't. -
Hunter B over 9 yearsI 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?
-
slm over 9 years@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 over 9 years@user3024130 - see updates.