Automate Textual Input from Bash Script Without Using EOF

bashlinuxshellshell-scriptUbuntu

I'm running Ubuntu Linux. Suppose there is a program called myprogram. This program prompts the user for input; specifically, the user must type an integer when prompted and press Enter. I would like to automate this process using a bash script. In particular, I would like to execute myprogram, say, 100 times (using a counter i which goes from 1 to 100). On each execution of myprogram, I would like to enter the current value of i when prompted.

(By the way, myprogram takes options/switches -options, all of which will be constant and thus specified within the bash script.)

An incomplete skeleton of this bash script might be:

#!/bin/bash
for i in {1..100}
do
   myprogram -options
done

Now I would like to modify the above code so that the current value of i is entered when prompted by the program. What is the best way to do this?

The website of the software I am using suggests using <<EOF at the end of the myprogram -options line. I think that this tells bash to look at the "end of the file" for the input to use. But what if I don't want to place the input at the end of the file? What if I would like to put it immediately after the << or <?

The reason is that things will get more complicated. For example, I may introduce an integer counter j that changes in some non-linear, non-sequential way. I would then want to feed the current value of j to myprogram on each iteration, but the value of j may change between the call to myprogram -options and the end of the file EOF.

Do you have any suggestions?

Best Answer

For nearly all programs, both echo $i | myprogram -options and myprogram -options <<<$i should work, by feeding the program $i through standard input.

<foo will use the contents of the file named foo as stdin.

<<foo will use the text between that and a line consisting solely of foo as standard input. This is a here document (heredoc), as Gilles said; EOF doesn't actually mean the end of the file, it's just a common heredoc delineator (we use "foo" instead in this example).

<<<foo will use the string "foo" as standard input. You can also specify a variable $foo, and the shell will use its contents as stdin, as I showed above. This is called a herestring, as it uses a short string in contrast to a whole block, as in a heredoc. Herestrings work in bash, but not in /bin/sh.

Related Question