Loop inside “heredoc” in shell scripting

﹥>﹥吖頭↗ 提交于 2019-12-08 02:34:01

问题


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

回答1:


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



回答2:


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.




回答3:


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


来源:https://stackoverflow.com/questions/38780931/loop-inside-heredoc-in-shell-scripting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!