Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop inside "heredoc" in shell scripting

I need to execute series of commands inside an interactive program/utility with parameterized values. Is there a way to loop inside heredoc ? Like below .. Not sure if eval can be of any help here. Below example doesn't seem to work as the interactive doesn't seem to recognize system commands.

#!/bin/sh
list="OBJECT1 OBJECT2 OBJECT3"
utilityExecutable << EOF
for i in $list ; do
utilityCommand $i
done
EOF
like image 316
Kevin Avatar asked Aug 05 '16 04:08

Kevin


People also ask

What is Heredoc in Shell?

Here document (Heredoc) is an input or file stream literal that is treated as a special block of code. This block of code will be passed to a command for processing. Heredoc originates in UNIX shells and can be found in popular Linux shells like sh, tcsh, ksh, bash, zsh, csh.

How does Bash implement Heredoc?

To use here-document in any bash script, you have to use the symbol << followed by any delimiting identifier after any bash command and close the HereDoc by using the same delimiting identifier at the end of the text.

What is Heredoc syntax?

The heredoc syntax is a way to declare a string variable. The heredoc syntax takes at least three lines of your code and uses the special character <<< at the beginning.

Which symbol is used for creating Heredoc?

The most common syntax for here documents, originating in Unix shells, is << followed by a delimiting identifier (often the word EOF or END), followed, starting on the next line, by the text to be quoted, and then closed by the same delimiting identifier on its own line.


1 Answers

Instead of passing a here-document to utilityExecutable, the equivalent is to pipe the required text to it. You can create the desired text using echo statements in a for-loop, and pipe the entire loop output to utilityExecutable:

#!/bin/sh

list="OBJECT1 OBJECT2 OBJECT3"

for i in $list; do
    echo "utilityCommand $i"
done | utilityExecutable
like image 92
janos Avatar answered Oct 07 '22 12:10

janos