0

In bash, I wish to check whether Python 2.7 is installed. While searching SO I found this: How do I test (in one line) if command output contains a certain string?

In bash, I have this:

python --version
Python 2.7.11

And so I tried this:

[[ $(python --version) =~ "2.7" ]] || echo "I don't have 2.7"
Python 2.7.11
I don't have 2.7

...which I found strange, as I expected that to work.

I also tried this:

if [[ $(python --version) =~ *2.7* ]]
    then
        echo "I have 2.7"
    else
        echo "I don't have 2.7"
fi

...which resulted in:

Python 2.7.11
I don't have 2.7

Hm! What am I doing wrong?

2 Answers 2

1

python --version command outputs to stderr.

You can redirect stderr to stdout prior to test:

if [[ $(python --version 2>&1) =~ 2\.7 ]]
    then
        echo "I have 2.7"
    else
        echo "I don't have 2.7"
fi
Sign up to request clarification or add additional context in comments.

Comments

1

You can do it the following way. You can first check if python is installed from the which command and then capture the output of python --version

if which python > /dev/null 2>&1;
then
    if [[ $(python --version 2>&1) == *2\.7\.11 ]]; then
       echo "Python version 2.7.11 is installed."
    fi 
else
    echo "No Python executable is found."
fi

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.