1

I have to install different modules according to the version of Python installed on a machine.

A previous question asked how to do this, but it only prints the result to screen. For instance:

$ python -c 'import sys; print sys.version_info'
sys.version_info(major=2, minor=7, micro=3, releaselevel='final', serial=0)

or rather:

$ python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))'
2.7.3

On a Bash shell, how can I "catch" the printed line above so that I can incorporate its value in an if-statement?

EDIT: OK, now I realize it was very simple. I got stuck initially with:

a=$(python --version)

... because it didn't assign anything to the variable a, it only printed the version to screen.

Community
  • 1
  • 1
Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185

3 Answers3

3

You can assign the value to a variable:

pyver=$(python -c 'import sys; print(".".join(map(str, sys.version_info[:3])))')

please, note that there are no spaces around the =.

Now, you can use it in your if statement:

if [[ "$pyver" == "2.7.0" ]]; then
    echo "Python 2.7.0 detected"
fi
Stefano Sanfilippo
  • 32,265
  • 7
  • 79
  • 80
1

Something like this:

if [[ $(python --version 2>&1) == *2\.7\.3 ]]; then
  echo "Running python 2.7.3";
  # do something here
fi

Note that python --version outputs to STDERR so you'd need to redirect it to STDOUT.

In order to assign it to a variable,

a=$(python --version 2>&1)
devnull
  • 118,548
  • 33
  • 236
  • 227
  • ooh ok, that's what I was missing. How could I have figured it out on my own that it was printing to STDERR? Just by guessing and trying? – Ricky Robinson Jan 21 '14 at 13:24
  • 1
    @RickyRobinson When it didn't redirect the output to the variable and printed on the screen instead, you could have said `python --version 2>/dev/null` to see what happens. – devnull Jan 21 '14 at 13:25
1

Use command substiution (`` or $()):

if [ $(python ...)  == 2.7.3 ]
then
 ...
fi
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144