wolfsgang
wolfsgang

Reputation: 894

Heredoc without quotes not expanding parameters

I am trying to create and use variables inside heredoc like this,

#!bin/bash
sudo su - postgres <<EOF
IP="XYZ"
echo "$IP"
EOF

This doesn't work right and I get a blank line as echo. But if I use quotes around EOF like this,

#!bin/bash
sudo su - postgres <<"EOF"
IP="XYZ"
echo "$IP"
EOF

It works. Can someone please explain this? According to what I read in man the behaviour should be opposite.

Upvotes: 2

Views: 628

Answers (1)

tripleee
tripleee

Reputation: 189327

The shell evaluates the unquoted here document and performs variable interpolation before passing it to the command (in your case, sudo). Because IP is not a defined variable in the parent shell, it gets expanded to an empty string.

With quotes, you prevent variable interpolation by the parent shell, and so the shell run by sudo sees and expands the variable.

Upvotes: 7

Related Questions