Unable to store "python --version" to a shell variable

Hi All,
I need to get the version of python installed and store it in a variable for later use. Whereas it is printing on the console instead of storing to variable. I am able to store output of ls command in a variable. Please check the below code :

root@myhost:/volumes/srini# cat python_version.sh 
python_version=python --version
echo "****"
echo $python_version
echo "****"
ls_output=ls -l python*
echo "****"
echo $ls_output
echo "****"

Please check the output of the code :

root@myhost:/volumes/srini# ./python_version.sh 
Python 2.6.8
****

****
****
-rwxr-xr-x 1 root root 147 May 26 09:35 python_version.sh
****

Please note, its able to store output of ls command in a variable, but not of python --version. Its directly displaying in console.

Regards,
Srinivasan

echo $python_verison

Hehe typos!

Ok what shell are you using, because so far not knowing I cant reply because of its behaviour: In shells I use (sh ksh...) your variable affectation would not work, and so you would not have any output for your ls part either

this is what I would have written:

python_version=$(python --version)
echo "****"
echo $python_version
echo "****"
ls_output=$(ls -l python*)
echo "****"
echo $ls_output
echo "****"

If you're using bash/sh or similar shells this will capture the python version number in a variable.

xx=$(python --version 2>&1)

The output is being sending to stderr, which is why you need the "2>&1".

1 Like

Thanks a lot cnamejj. I am using bash shell and redirection of stderr worked.