Friday, April 27, 2012

Script a script and pass inputs

I often have scripts written that do something based on user inputs.  What I want to talk about today is how to use another script to call the first script and provide the user inputs.  That way I can call the scripts a bunch of times and not have to tediously type similar things over and over.  And even better, the way to do this is pretty easy!

Ok here it goes.  Imagine you have a script called repeater that takes a user input and gives it back (not very useful but easy to test with).

Here is my script.
#!/bin/bash
# Repeater

echo "Enter something for me to repeat"
read -e text
echo "You said: $text"

If you call the script, it prompts you for an input and then repeats what you said.  For example
>>./repeater
Enter something for me to repeat
apple
You said: apple


Now here is the interesting part.  We're going to call the script and provide the input, all with one command.
>> ./repeater << EOF
> apple
> EOF


If you want to put this in a script it could look like this
#!/bin/bash

./repeater << EOF
apple
EOF

./repeater << EOF
bannana
EOF

./repeater << EOF
kiwi
EOF

If your script requires multiple user inputs, put them on different lines, e.g.,
>> ./repeater_multiInputs << EOF
> input 1
> input 2
> input 3
> EOF