Passing arguments to an interactive script to make it non interactively

How to

Many scripts, require input from the user, or give output to the user as the script is running. This article describe how to pass arguments to script and make it non interactively, when we already know answers and we want to go thru script faster.

Making scripts which require inputs.

At first we create basic script which require one or two argument it will depends on the responds given by user. For better understanding click for this article Creating interactive “yes” or “no” SHELL script.

#!/bin/sh

read -p 'script will be terminated after "no" and continue after "yes" ' opt

while true; do
case $opt in

[yes]* ) echo 'after "yes" program continue ';;

[no]* ) echo 'program read "no" and will be terminated '; exit;;

* ) echo 'Please answer yes or no. ';;

esac

read -p 'another option ' opt

done

As we can see, scripts do nothing meaningful, but perfectly suits for us.

Passing inputs.

There are many ways how to pass inputs to the script, first one is just run script and pass input manually.

# ./opt.sh
script will be terminated after "no" and continue after "yes" yes
after "yes" program continue
another option no
program read "no" and will be terminated
#

But when we want to safe time and we are running script often with known answers, we can do it automatically.

For one input we can pipe it by ‘echo’.

# echo no | ./opt.sh
program read "no" and will be terminated
#

For more inputs we can pipe it by “printf” where ‘\n’ means new line

# printf "yes\nyes\nno" | ./opt.sh
after "yes" program continue
after "yes" program continue
program read "no" and will be terminated
#

Or we can redirect answers.

# ./opt.sh <<< $'yes\nyes\nno'
after "yes" program continue
after "yes" program continue
program read "no" and will be terminated
#

For another example we will use more lines a nd redirection.

# ./opt.sh << ANSWERS
yes
yes
no
ANSWERS
after "yes" program continue
after "yes" program continue
program read "no" and will be terminated
#

And the last example will use file with answers.

# cat ans.txt
yes
yes
no
#
#
# ./opt.sh < ans.txt
after "yes" program continue
after "yes" program continue
program read "no" and will be terminated
#

All of these examples are showing us how to pass arguments to script by avoiding to interact with script.

 

Leave a Reply