I'm running bash.
- Suppose I have a binary
mybinarythat takes interactive user input. - Suppose that
mybinarytakes attendee names as input until the user typesqand presses Enter (qfor "quit"). - I can automate the input process in a bash script by surrounding the input by
<<EOF/EOF. For example, suppose I want to enter predefined user input from an arraymyarray. I can do:
#!/bin/bash
myarray=("Alice" "Bob" "Charlie" "q") # q quits the binary
mybinary -f inputfile.txt -o outputfile.txt<<EOF
${myarray[0]}
${myarray[1]}
${myarray[2]}
${myarray[3]}
EOF
I tested the above, and it works. But it's laborious to type ${myarray[X]} for every index in myarray if myarray has hundreds of (string) elements.
How can I modify the above bash script to loop through myarray?
The following won't work because the for, do, and done parts will be taken as input to mybinary:
#!/bin/bash
myarray=("Alice" "Bob" "Charlie" "q") # q quits the binary
mybinary -f inputfile.txt -o outputfile.txt<<EOF
for element in "${myarray[@]}"
do
${myarray[0]}
${myarray[1]}
${myarray[2]}
${myarray[3]}
done
EOF
Moreover, I can't simply place the for loop around the call to mybinary, because I don't want multiple calls to mybinary. So how can I loop through an array to use the array's elements as input to mybinary?
mybinaryis reading lines from stdin, wouldn'tprintf '%s\n' "${myarray[@]}" | mybinary -f inputfile.txt -o outputfile.txtsuffice?for x in "${myarray[@]}"; do echo "$x"; done