I'm writing a CLI script that asks a series of questions before doing a few things. How can I pass them as arguments so that I don't have to keep entering them every time I want to test my script?
Basically, it should pass 4 items to STDIN, like "text1[ENTER]text2[ENTER]text3[ENTER]text4[ENTER]" automatically.
Yes, I could modify my script to actually read the shell arguments, but I don't want to do it that way, since it's supposed to run more like a wizard.
Looking for something like
SOMEPROGRAM myscript arg1 arg2 arg3 arg4
or
SOMEPROGRAM arg1 arg2 arg3 arg4 | myscript
Or something like that. Is there such a program?
I understand you do not want to modify
myscript
.Regarding the second solution you ask for, you can use
printf
:so that, defining an alias for SOMEPROGRAM as:
you could effectively call
The first form is ambiguous (from the point of view of SOMEPROGRAM), because it don't know where
myscript
options end and text parameters start, unlessmyscript
is effectively invoked without any options. In this case you could use a function:so that you could effectively call
So basically, you want to pass each argument as a line to a child program. Below is a script that loops through all arguments passed ti
SOMEPROGRAM
and prints them as a line. You can pass an empty line ("enter without entering something before") by passing an empty argument as inSOMEPROGRAM yes '' | myscript
.If you always need to answer "yes" to your script, use the coreutil
yes
:If you need to pass some other value, say "no":
You can pass the parameters, but it won't work, you'll also have to modify the bash script to accept the params from the command-line as well.
If you are writing a script then just use getopts so the arguments are passed to the scripts and then you can use those args as you want? Is this something you are looking for?
http://wiki.bash-hackers.org/howto/getopts_tutorial
For simple cases, the way enzotib describes it with piping stdin from a file seems reasonable. Consider this script:
invoke it with:
The -e is to enable escape sequences like
\n
ewline.Note how magically, bash doesn't print the prompt for reading.
However, for more complicated cases, there is a program, called
expect
to handle interactive CLI programs, where you have to wait for the next prompt, before entering the second value, and I guess you can even branch under conditions.With bash, you can do this:
or
I'm pretty sure you're looking for expect.
edit: example added
--from this blog