代码之家  ›  专栏  ›  技术社区  ›  hjpotter92

shell脚本未将命令输出存储为变量

  •  0
  • hjpotter92  · 技术社区  · 8 年前

    我定义了一个函数来检查环境变量 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
    }
    

    但是,这只是输出 python -V 而不是将其存储到变量中。打印整个堆栈( 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%})'
    

    类似的函数来获取我 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
    }
    

    在哪里? rbenv_prompt_info 来自 oh-my-zsh plugin .

    1 回复  |  直到 8 年前
        1
  •  2
  •   andreee    8 年前

    python -V 打印到 stderr 不是 stdout 。您需要将标准错误重定向到标准输出,否则将得到一个空字符串。

    使用 local VERSION=$(python -V 2>&1) 相反。