Reputation: 37118
There is a command line node script I use at work which, when run, asks a series of prompts, one after the other, before executing. Example:
$ npm run-script scriptname
Give me some information:
<me typing stuff and pressing enter>
Give me some more information:
<me typing some more stuff and pressing enter>
Now running script.
Script complete.
$
I'm trying to write a bash script that auto-fills these fields but I'm not sure how to do that. So within the bash script I do:
npm run-script scriptname
But after that I need to handle the interactive input phase and I'm not sure how, or what to google to find out. Does anyone have any insight into how this is done?
Using echo "info1 info2" | npm run-script scriptname
simply gives the string "info1 info2"
to the first prompt and hangs on the second waiting for me to complete it. Changing the space to a newline yields the same behavior.
Upvotes: 2
Views: 178
Reputation: 69426
Just for completeness, because this wasn't mentioned in any other answer and it's perhaps the simplest way:
echo "info1
info2" | npm run-script scriptname
should also work (you just press after opening ").
Upvotes: 0
Reputation: 362197
How did you add a newline? If you did
echo "info1\ninfo2" | npm run-script scriptname
that won't work because \n
is the literal characters \
and n
. Instead use one of these:
echo $'info1\ninfo2' | npm run-script scriptname
echo -e "info1\ninfo2" | npm run-script scriptname
The first tells bash to interpret the \n
as a newline; the second has echo
do the interpretation.
Another way to pass multiple lines of input is with here document syntax:
npm run-script scriptname <<INPUT
info1
info2
INPUT
If none of these work then that means the program you're running isn't reading from stdin, but instead is reading directly from the tty. SSH does this intentionally to make it harder to automate password entry since having passwords in scripts is a major security hole.
If that's what's happening then my first recommendation is to figure out another way to get the program to do what you want. It's probably got a good reason it's avoiding stdin. Perhaps there are command-line flags you could use to control it, or a configuration file.
If not, then you could use Expect.
Expect is a tool for automating interactive applications such as telnet, ftp, passwd, fsck, rlogin, tip, etc. Expect really makes this stuff trivial....
Expect can make easy all sorts of tasks that are prohibitively difficult with anything else. You will find that Expect is an absolutely invaluable tool - using it, you will be able to automate tasks that you've never even thought of before - and you'll be able to do this automation quickly and easily.
Upvotes: 2