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?
CodePudding user response:
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 ...
CodePudding user response:
Include the next line in your script
which python2 || { echo "pyhon2 not installed or in PATH"; echo exit 1; }
CodePudding user response:
The redirection is for the stdout/stderr of the python2 process. If python2 doesn't exist, there is no python2 process, so the redirection never happens .
If you want to capture shell error messages related to problems creating a process, you need to use a subshell:
sh -c 'python2 -V' 2>&1 |
sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'