简体   繁体   English

在 shell 脚本中循环“heredoc”

[英]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?有没有办法在 heredoc 中循环? Like below.. Not sure if eval can be of any help here.如下所示.. 不确定eval在这里是否有任何帮助。 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

Instead of passing a here-document to utilityExecutable , the equivalent is to pipe the required text to it. 与其将此处的文档传递给utilityExecutableutilityExecutable将所需的文本传递给它。 You can create the desired text using echo statements in a for-loop, and pipe the entire loop output to utilityExecutable : 您可以在for循环中使用echo语句创建所需的文本,并将整个循环输出通过管道传递到utilityExecutable

#!/bin/sh

list="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/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. 这是因为Heredoc使用了自己的变量,这些变量与Shell完全分开。 When you are inside heredoc, you have to use and modify heredoc's own variables. 当您进入heredoc时,必须使用和修改heredoc自己的变量。 So the \\$ is needed to reference heredoc's own variables instead of shell variables when inside heredoc. 因此,在heredoc中时,需要\\ $引用heredoc自己的变量,而不是shell变量。

cat << EOF
$(
    for i in {1..10}; do
        echo $i;
    done
)
EOF
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
myVar=$(
    for i in {1..5}; do
        echo hello;
        echo world;
    done;
); cat <<< $myVar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM