'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
Solution 1:[1]
Yes, this is tricky and can be confusing! You have to modify your codes as follow.
#!/bin/sh
list="OBJECT1 OBJECT2 OBJECT3"
utilityExecutable << EOF
list="$list"
for i in \$list ; do
utilityCommand \$i
done
EOF
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.
Solution 2:[2]
commandxyz -noenv<<EOF
echo "INFO - Inside eof"
t_files=("${p_files[@]}")
#copy array
#echo \${t_files[*]}
#all elements from array
#echo \${#t_files[@]}
#array length
for i in \${t_files[@]} ; do
echo -e \$i;
do other stuff \$i;
done
cat $patch_file
git apply $patch_file
EOF
Solution 3:[3]
cat << EOF
$(
for i in {1..10}; do
echo $i;
done
)
EOF
Solution 4:[4]
myVar=$(
for i in {1..5}; do
echo hello;
echo world;
done;
); cat <<< $myVar
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kwan-yin Kong |
| Solution 2 | vasu |
| Solution 3 | Raz Kheli |
| Solution 4 | Raz Kheli |
