wolfsgang wolfsgang - 6 months ago 17
Bash Question

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.

Answer

The shell evaluates the unquoted here document and performs variable interpolation before passing it to 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.

Comments