Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Array Elements To Heredoc

I'm trying to pass an array elements to heredoc, the goal is to produce a file, for example:

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

Is this possible?, How can i achieve this?

like image 547
Haroldo Payares Salgado Avatar asked Jan 20 '26 10:01

Haroldo Payares Salgado


1 Answers

You can nest a loop with $(..):

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

When executed, this produces a test.txt containing:

Greetings,

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

Happy New Year from myusername
like image 141
that other guy Avatar answered Jan 23 '26 04:01

that other guy