为什么shell脚本中的变量从python的结果看起来很奇怪?

Seo*_* So 1 python linux bash shell

我试图从python的结果中获取bash shell中的变量.这是我的python代码:

print '** it is python testing **'
Run Code Online (Sandbox Code Playgroud)

我制作了一个shell脚本.当我正常使用时,它会显示非常正确的结果.

#!/bin/bash
python pytest.py
Run Code Online (Sandbox Code Playgroud)

结果: ** it is python testing **

但是,当我把它作为shell中的变量时,它显示出奇怪的结果.这是脚本:

#!/bin/bash
#python pytest.py

PYTEST="$(python pytest.py)"
echo $PYTEST
Run Code Online (Sandbox Code Playgroud)

然后结果看起来像这样:

ptest.sh pytest.py it is python testing ptest.sh pytest.py

我从其他复杂的代码尝试了它,但结果几乎相同.shell脚本中的变量始终显示目录中的一些文件.我不擅长shell脚本,但不明白为什么.(我使用的是GNU bash,4.1.10版本)

有人能帮帮我吗?提前致谢 :)

Cha*_*ffy 6

如果你没有引用你的扩展,那么它们就是字符串拆分和全局扩展."全局扩展"意味着像*更改为文件名列表之类的东西.

所以,引用:

echo "$PYTEST"
Run Code Online (Sandbox Code Playgroud)

...将精确输出作为单个字符串传递.

没有引用:

echo $PYTEST
Run Code Online (Sandbox Code Playgroud)

......将首先扩展:

echo ** it is python testing **
Run Code Online (Sandbox Code Playgroud)

...然后将**s 更改为文件名列表,然后调用echo.


请注意,即使没有通配,字符串拆分也会产生意外的影响.假设您的Python程序执行了以下操作:

print "      it is python testing"
Run Code Online (Sandbox Code Playgroud)

你可能希望echo $PYTEST在这种情况下工作正常......但相反,你会看到它丢弃了领先的空白:

> echo $PYTEST
it is python testing
Run Code Online (Sandbox Code Playgroud)

为什么?因为串分解打破了输入分解成单词,并将每个单词作为单独的参数来呼应,和回声加入它的参数与每个之间的一个空间.

所以,就像下面的空白一样:

> echo       it is     python testing
it is python testing
Run Code Online (Sandbox Code Playgroud)

...对于符合POSIX标准的shell中的不带引号的扩展也是如此.(zsh的,顺便说一下,并没有与POSIX在这方面的规定,并含蓄地把扩张,好像他们是引用).