0

So suppose a normal command run in terminal goes like this....

user$ thecommand
Please enter your first name:
>

and then waits for your to type your name... straightforward, but if in a bash script I try and do something like:

#! /bin/bash
 echo "What is your name?"
     read name
 thecommand

how would I have THE SCRIPT enter "$name" in response to "thecommand" instead of having the user manually input it themselves?

driedupsharpie
  • 133
  • 2
  • 10

3 Answers3

1

you can add input by pipe like this:

echo yourname | ./yourscript

for more inputs you can use printf

printf "input1\ninput2" | ./yourscript

where \n means new line and it will be used like new input.

vlp
  • 583
  • 3
  • 8
0

Run your script like:

./yourscript.sh < file.txt

where file.txt will contain the name.

now your script will look for name from the file(file.txt), in file.txt you can type the names which will act as input for read command. read command reads on line at a time so if u have more than on read command in your script you should have multiple lines in file.txt file

antrax
  • 1
  • 1
  • I like the look of this method! So would it work if I had ./myscript write a few lines to a file.txt, and then ran: user$ thecommand < file.txt ?? – driedupsharpie Jul 28 '15 at 11:19
0

For complicated cases, for example if your input depends on the output of your command, you may write an "expect" script.

To see how it works you can auto-generate such script interactively

$ autoexpect thecommand

And then run it

$ expect -f script.exp

rudimeier
  • 854
  • 1
  • 8
  • 20