[英]shell script not storing command output as variable
I have defined a function to check if the environment variable VIRTUAL_ENV
is set, and if so, figure out the current python version. 我定义了一个函数来检查是否设置了环境变量VIRTUAL_ENV
,如果已设置,请找出当前的python版本。
theme_python_prompt () {
if [ -v VIRTUAL_ENV ]
then
local VERSION="$(python -V)"
echo -n "%{$fg[yellow]%}%{$reset_color%}:${VERSION}(%{$fg[magenta]%}$(basename ${VIRTUAL_ENV})%{$reset_color%})"
fi
}
But, this is just outputting the result of python -V
to stdout instead of storing it into the variable. 但是,这只是将python -V
的结果输出到stdout而不是将其存储到变量中。 Printing the whole stack ( set -x
) shows the following: 打印整个堆栈( set -x
)显示以下内容:
+theme_python_prompt:1> [ -v VIRTUAL_ENV ']'
+theme_python_prompt:3> python -V
Python 2.7.15
+theme_python_prompt:3> echo ''
+theme_python_prompt:3> local VERSION=''
+theme_python_prompt:4> basename /home/hjpotter92/.virtualenvs/test-2fI9Fep8
+theme_python_prompt:4> echo -n $'%{\C-[[33m%}%{\C-[[00m%}:(%{\C-[[35m%}test-2fI9Fep8%{\C-[[00m%})'
A similar function to fetch me rbenv
info is working without issues: 一个类似的获取我rbenv
信息的功能可以正常工作:
theme_rbenv_prompt () {
if ! type rbenv > /dev/null
then
echo -n ""
else
local VERSION="$(rbenv_prompt_info)"
[ "$VERSION" != "system" ] && echo "%{$fg_bold[red]%}%{$reset_color%}:${VERSION} " || echo -n ""
fi
}
where rbenv_prompt_info
is from oh-my-zsh plugin . 其中rbenv_prompt_info
来自oh-my-zsh插件 。
python -V
prints to stderr
, not stdout
. python -V
打印到stderr
而不是stdout
。 You need to redirect the standard error to standard output, otherwise you'll get an empty string. 您需要将标准错误重定向到标准输出,否则将得到一个空字符串。
Use local VERSION=$(python -V 2>&1)
instead. 请改用local VERSION=$(python -V 2>&1)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.