bash run script from here doc [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-20 06:27:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!