0

In the code below, variable X is output normally.

# cat a.sh
X=world
echo 'hello' $X

# cat a.sh | bash
hello world

But, using here doc, variable X is not displayed.

# cat <<EOF | bash
> X=world
> echo 'hello' $X
> EOF
hello

# bash -s <<EOF
> X=world
> echo 'hello' $X
> EOF
hello

What made this difference?

이화섭
  • 11
  • 1
  • 2
  • The opposite problem (but the answer should still help you): https://stackoverflow.com/questions/4937792/using-variables-inside-a-bash-heredoc – melpomene Mar 16 '19 at 09:23

1 Answers1

2

You can see what happens when you remove the |bash

X=oldvalue
cat <<EOF 
X=world
echo "hello $X"
EOF

The $X is replaced before piping it to bash.
You can check the following

X=oldvalue
cat <<"EOF"
X=world
echo "hello $X"
EOF

This is what you want to execute:

cat <<"EOF" | bash
X=world
echo "hello $X"
EOF
Walter A
  • 19,067
  • 2
  • 23
  • 43