hjpotter92
hjpotter92

Reputation: 80653

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.

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. Printing the whole stack (set -x) shows the following:

+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:

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.

Upvotes: 1

Views: 286

Answers (1)

andreee
andreee

Reputation: 4679

python -V prints to stderr, not 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.

Upvotes: 3

Related Questions