Simulate user input in bash script

118,933

Solution 1

You should find the 'expect' command will do what you need it to do. It's widely available.

A very rough example:

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

Solution 2

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"
Share:
118,933
Werulz
Author by

Werulz

Updated on November 12, 2021

Comments

  • Werulz
    Werulz over 2 years

    I am creating my own bash script, but I am stuck at the moment. Basically, the script would be used to automate server setup in CentOS. Some software normally asks the user to type a password. I want the script to put the password that I have generated and stored as a variable instead of asking the user.

    When the message "New password:" appears during install, how can I make the script put the value stored in a variable $key as if the user had typed it, with a bash script?