Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to store python --version to a shell variable [duplicate]

Tags:

bash

shell

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_verison
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
\****
like image 746
user3674997 Avatar asked Feb 13 '23 21:02

user3674997


2 Answers

Seems like that value gets sent to stderr for some reason, as in this question.

I find that the following seems to work:

python_version=$(python --version 2>&1)
echo "\****"
echo $python_version
echo "\****"

gives

\****
Python 2.7.3
\****
like image 191
tasteslikelemons Avatar answered Apr 27 '23 23:04

tasteslikelemons


The value of python_version is set locally when the script is run. It has no impact on the invoking shell. If you want that variable to be set in the current shell, you can accomplish that using one of the following methods.

  1. Run the following command in your current shell.

    python_version=$(python --version 2>&1)
    
  2. Create a file that contains the above line. Say that file is python_version.sh. Then execute:

    source python_vesion.sh
    
like image 20
R Sahu Avatar answered Apr 28 '23 01:04

R Sahu