1

I want to get and parse the python (python2) version. This way (which works):

python2 -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'

For some reason, python2 is showing the version using the -V argument on its error output. Because this is doing nothing:

python2 -V | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'

So it needs to be redirected 2>&1 to get parsed (stderr to stdout). Ok, but I'd like to avoid the error shown if a user launching this command has no python2 installed. The desired output on screen for a user who not have python2 installed is nothing. How can I do that? because I need the error output shown to parse the version.

I already did a solution doing before a conditional if statement using the hash command to know if the python2 command is present or not... so I have a working workaround which avoids the possibility of launching the python2 command if it is not present... but just curiosity. Forget about python2. Let's suppose is any other command which is redirecting stderr to stdout. Is there a possibility (bash trick) to parse its output without showing it if there is an error?

Any idea?

OscarAkaElvis
  • 5,384
  • 4
  • 27
  • 51
  • 1
    Testing for command existence/validity is the way. Maybe, instead of an `if` you could something like `python2 -V &>/dev/null && python2 -V | sed ...`. Another thing you could do is to add a grep to select the version line (or to kill the other error lines), but that is fully dependent on the command being run and the OS, no general solution. – Poshi Sep 11 '22 at 10:37
  • our question could have been a lot shorter. You don't care about `python` or `stderr`. – Walter A Sep 11 '22 at 11:36
  • For getting Python's version number, try https://stackoverflow.com/questions/1252163/printing-python-version-in-output – tripleee Sep 11 '22 at 12:25

2 Answers2

2

Print output only if the line starts with Python 2:

python2 -V 2>&1 | sed -n 's/^Python 2\.\([0-9]*\).*/2\1/p'

or,

command -v python2 >/dev/null && python2 -V 2>&1 | sed ...
M. Nejat Aydin
  • 9,597
  • 1
  • 7
  • 17
1

Include the next line in your script

command python2 >/dev/null 2>&1 || {echo "python2 not installed or in PATH"; exit 1; }

EDITED: Changed which into command

Walter A
  • 19,067
  • 2
  • 23
  • 43
  • 2
    `which` is not properly standardized; it may not exist, or not work correctly. The POSIX equivalent is `command`, or, for some use cases, `type`. – tripleee Sep 11 '22 at 12:52