问题
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?
回答1:
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
来源:https://stackoverflow.com/questions/55195182/bash-run-script-from-here-doc