Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I create a shell script containing some commands which need user input, for example

useradd test
passwd test

The passwd command needs some input (the password). Can I serve this input via the shell script? Thank you!

share|improve this question
up vote 1 down vote accepted

The passwd command is specifically protected against this (I believe in order to reduce it's utility in brute-force password guessing attacks). It reads it's input only from a connected terminal and not from the usual STDIN - this makes it difficult to use it to script password changes.

But see the man page for usermod

share|improve this answer
So this is theoretically possible but especially not for setting passwords? – strauberry Sep 28 '11 at 13:15
Yes, you can write a script that prompts for user input and which reads that user input into a variable. You can also write an interactive script that invokes passwd but, in that case, your script doesn't get to see any part of passwd's user interaction and can't feed password values into passwd. – RedGrittyBrick Sep 28 '11 at 13:19
@strauberry: Answer updated – RedGrittyBrick Sep 28 '11 at 13:22

Normally not since most programs which require a password will not read from stdin as regular UNIX processes do. Instead they will try to read in the password from the controlling tty.

If you want to script such applications you will have to use tools like expect.

share|improve this answer


$ ./ foo bar baz



echo $0       #
echo $1       # foo
echo $3       # baz
share|improve this answer
So I could do something like this: passwd test echo $2 ? – strauberry Sep 28 '11 at 13:12
As answered by the others, no, this script is just to show how you can pass arguments into the script. – Jin Sep 28 '11 at 13:18
$argv[1] is not valid syntax in bash. $1 is the only proper way. – grawity Sep 28 '11 at 13:24
@grawity Thanks, fixed. Silly me, I've been using zsh. – Jin Sep 28 '11 at 13:25

Use expect. An example here

set username [lindex $argv 0]
set newpass [lindex $argv 1]
spawn passwd $username
expect {*password:}
send "$newpass\r"
expect {*password:}
send "$newpass\r" 
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .