0

Objective: to get python version in shell script

Observation:

[root@srvr0 ~]# python --version
Python 2.7.5

Code:

export python_version=`python --version`
echo "\$python_version=$python_version"

Expected:

$python_version=Python 2.7.5

Actual:

$python_version=

Please help me getting python version in shell script.

1
  • Also note, some Linux distributions use different binary names for python and, e.g. python2. If you have a need for one or the other, it's worth checking how your distribution handles the naming. Commented Feb 22, 2020 at 2:56

2 Answers 2

2

the --version writes to stderr, so:

export python_version=$(python --version 2>&1)
Sign up to request clarification or add additional context in comments.

Comments

0

The command output being in stderr rather than stdout really tripped me up for a while; definitely wasn't expected behavior for me.

Anyways, if anyone comes here trying to do this on Windows, you can do this:

for /f "USEBACKQ tokens=2" %G in (`"python --version 2>&1"`) do set pyVersion=%G

You'll then have a string like '2.7.18' in the pyVersion variable. Remember to expand %G to %%G if using it within a batch script.

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.