2

I've done this before.

I've read numerous posts in this forum, and googled even more on how to save the result of a shell command into a variable. All of them say to do this

VAR="$(shell_command)"
echo $VAR

or

VAR=`shell_command`
echo $VAR

But I'm trying to do this

VAR="$(python2.7 -V)"
echo "Version is $VAR"

or

VAR=`python2.7 -V`
echo "Version is $VAR"

and I see

Python 2.7.14
Version is

IOW I'm not storing the result? Why is this? I just want pure bash and want to understand why it doesn't do what I expect it to do. Thanks!

2 Answers 2

4

In this particular case, it's because Python prints the version to its standard error stream. The $(...) construction (or backticks) only captures what the given command sends to standard output.

You can get around this, in this case, by writing $(python2.7 -V 2>&1). Here 2>&1 is shell code that means "replace the standard error stream with a copy of the standard output stream", so anything Python thinks it's writing to standard error actually goes to the destination that standard output goes to.

Note that in some cases, similar problems can result from improper use of quotes. In general it's a good idea to surround command substitutions with double quotes:

VAR="$(python2.7 -V 2>&1)"

It turns out not to matter in this case though.

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

python2.7 -V >/dev/null

And you'll still see the output, which means that the version info is not sent to standard output (stdout).

And this:

python2.7 -V 2>/dev/null

The output is gone, further confirming that it's sent to standard error.

So you would like to do this:

VAR="$(python2.7 -V 2>&1)"
#                  ^^^^
# Redirect stderr to stdout

which works for me.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.