weera
weera

Reputation: 942

Pushing a new value to array inside heredoc in Bash

Assume I have this block of Bash code:

arr=(a b c)
sudo -i -u username bash <<EOF
  arr[${#arr[@]}]="d"
EOF

I need to add "d" to arr inside heredoc. But it is not working.

Upvotes: 0

Views: 204

Answers (1)

KamilCuk
KamilCuk

Reputation: 141135

You can pass the context to another session.

arr=(a b c)
sudo -i -u username bash <<EOF
$(declare -p arr)
arr[\${#arr[@]}]="d"
EOF

or like:

arr=(a b c)
DATA=$(declare -p arr)
export DATA
sudo --preserve-env=DATA -i -u username bash <<'EOF'
eval "$DATA"
arr[${#arr[@]}]="d"
EOF

Upvotes: 1

Related Questions