2

I am creating an install script where I would like to compare the version of installed default Python with the version I need to have running. Currently here is my code:

#!/bin/bash
PYTHON="$(python -V)"
if [[ "$PYTHON = 'Python 2.7.6' ]]
then echo "Python is installed."
else echo "Python is not installed."
fi

The response I keep getting is that Python is not installed, but that is the output when I type in the command python -V.

Any help is greatly appreciated. Thank you in advance.

Jahid
  • 21,542
  • 10
  • 90
  • 108

2 Answers2

3

It seems that when you run python -V, it prints the version to stderr, not to stdout. So, changing your attempt to capture the output into a variable to this:

PYTHON=$(python -V 2>&1)

should do the trick. Another alternative, which tends to include additional information about build dates, compilers, etc. would be:

python -c 'import sys; print sys.version'

or, as suggested by @chepner:

python -c 'import sys; print sys.version_info'

Both of these would require a little additional parsing to get the specific information you want/need, though.

twalberg
  • 59,951
  • 11
  • 89
  • 84
0

You can change your code like this:

#!/bin/bash
PYTHON="$(python -V 2>&1)"
if [[ "$PYTHON" = "Python 2.7.6" ]]; then
    echo "Python is installed."
else
    echo "Python is not installed."
fi
Jahid
  • 21,542
  • 10
  • 90
  • 108
  • While this lets me know that Python is installed, I need to know the specific version installed. I am creating the script to automate the installation process of Jekyll for Windows users and Python 2.7.* works where Python 3.* does not. – Joseph Preston May 15 '15 at 12:03
  • @Jahid your explanation of `exit` and what gets fed to the `bash` "capture standard output and assign it to a variable" construct (i.e. `$(...)`) is incorrect. – twalberg May 15 '15 at 15:18
  • 1
    don't use `which` to check command existence: http://stackoverflow.com/questions/592620/check-if-a-program-exists-from-a-bash-script – Jason Hu May 15 '15 at 15:20
  • Can you explain a little, @twalberg – Jahid May 16 '15 at 00:50
  • @twalberg, Due to having doubt about my theory I removed that portion, but still I need an explanation, if you may... – Jahid May 16 '15 at 00:57
  • 1
    @Jahid `PYTHON=$(...)` captures the standard output of a program, which, by token of the fact that `${PYTHON}` was ending up empty, demonstrates the fact that `python -V` in fact produces no output on standard output (it goes to standard error, instead). The exit library call returns an exit code to the shell, which is a different concept than writing something to the output. This is somewhat confused by the fact that Python provides an overloaded `exit()` call such that `exit('foo')` is roughly equivalent to `print 'foo'; exit()`... – twalberg May 16 '15 at 02:23