mad7
mad7

Reputation: 58

Is it possible to have variable substitution in a nested heredoc?

I have a bash script of this structure:

ssh user1@host <<EOF1
    var1="abc"
    echo \$var1

    su user2 <<EOF2
        var2="xyz"
        #echo var2 (how?)
        ..do something..
EOF2
EOF1  

Now I'm able to define and access the variables inside the outer heredoc EOF1 as shown. Is it possible do the same inside inner heredoc EOF2?

This is what I do in my script : I execute a command inside the EOF2 as a different user, get the exit code of that command and store it in a variable for further checks inside EOF2 block. But I'm stuck in storing the exit code of command into a variable and accessing it later. Any other way of doing this would also be of great help. Thanks.

Upvotes: 3

Views: 474

Answers (1)

DaBler
DaBler

Reputation: 2850

Yes, just add a backslash:

echo \\\$var2

which is transformed (within the outer heredoc) into:

echo \$var2

and finally inside the inner heredoc into:

echo $var2

Upvotes: 2

Related Questions