Loop inside "heredoc" in shell scripting Loop inside "heredoc" in shell scripting shell shell

Loop inside "heredoc" in shell scripting


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/shlist="OBJECT1 OBJECT2 OBJECT3"for i in $list; do    echo "utilityCommand $i"done | utilityExecutable


Yes, this is tricky and can be confusing! You have to modify your codes as follow.

#!/bin/shlist="OBJECT1 OBJECT2 OBJECT3"utilityExecutable << EOF  list="$list"  for i in \$list ; do    utilityCommand \$i  doneEOF

This is because heredoc uses its own variables, which are completely separate from the shell. When you are inside heredoc, you have to use and modify heredoc's own variables. So the \$ is needed to reference heredoc's own variables instead of shell variables when inside heredoc.


commandxyz -noenv<<EOFecho "INFO - Inside eof" t_files=("${p_files[@]}")#copy array#echo \${t_files[*]} #all elements from array#echo \${#t_files[@]}#array lengthfor i in \${t_files[@]} ; do        echo -e \$i;        do other stuff \$i;donecat $patch_filegit apply $patch_fileEOF