shell脚本不能将命令行的输出保存到变量中 [英] shell script can not save output from command line into variable
问题描述
我试图做shell命令,然后使用shell脚本将输出保存到变量。所以我使用这样的反引号:
out =`ls -l`
print $ out
该代码工作正常,我可以使用它任何其他shell命令,但是当我尝试做'python - -version'来检查python版本。我有奇怪的问题。 backtick不工作的python --version命令,当它与任何其他命令工作正常,它打印输出到屏幕,并不保存任何变量$ out。所以如果我这样做:
out =`python --version`
printmy python version is
结果:
code> Python 2.6.1
我的python版本是
使用$()来替换backtick,但没有运气。任何想法?
您的等号之前有一个空格:
out =`python --version`
:
out =`python --version`
更新
此外,python会将版本字符串输出到stderr,到stdout:
out =`python --version 2>& 1`
i'm trying to do shell command then save the output into variable using shell script. So i use backticks like this :
out=`ls -l`
print $out
that code is working fine,and i can use it for any other shell command, but when i try to do 'python --version' to check python version. i got weird problem. The backtick is not working for "python --version" command while it's working fine with any other commands, it prints the output to the screen and save nothing to the variable $out. so if i do :
out =`python --version`
print "my python version is "$out
result:
Python 2.6.1
my python version is
also i tried to use $() to replace backtick , but no luck. Any idea ?
You have a space before your equals sign:
out =`python --version`
Should be:
out=`python --version`
Update
Also python outputs the version string to stderr, so you need to redirect it to stdout:
out=`python --version 2>&1`
这篇关于shell脚本不能将命令行的输出保存到变量中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!