Reputation: 381
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?
Upvotes: 2
Views: 1406
Reputation: 15213
You certainly can
cat > test.txt <<-EOF
some text, ${box[0]}
some text, ${box[1]}
some text, ${box[2]}
EOF
Upvotes: 3
Reputation: 123480
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
Upvotes: 6