将数组元素传递给Heredoc

时间:2019-01-03 21:19:22

标签: linux bash heredoc

我正在尝试将数组元素传递给heredoc,目标是生成一个文件,例如:

declare -a box=("element1" "element2" "element3")

cat > test.txt <<-EOF
some text, insert first element
some text, insert second element
some text, insert third element
EOF

这可能吗?,我该如何实现?

2 个答案:

答案 0 :(得分:3)

您当然可以

cat > test.txt <<-EOF
some text, ${box[0]}
some text, ${box[1]}
some text, ${box[2]}
EOF

答案 1 :(得分:2)

您可以使用$(..)嵌套循环:

declare -a box=("element1" "element2" "element3")

cat > test.txt <<-EOF
Greetings,

Here are the elements you wanted:
$(
    for s in "${box[@]}"
    do
      echo "some text, $s"
    done
 )

Happy New Year from $USER
EOF

执行后,将产生一个test.txt,其中包含:

Greetings,

Here are the elements you wanted:
some text, element1
some text, element2
some text, element3

Happy New Year from myusername