Chris F
Chris F

Reputation: 16822

Why am I not saving the result of the shell command into my variable?

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!

Upvotes: 2

Views: 1452

Answers (2)

iBug
iBug

Reputation: 37317

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.

Upvotes: 1

David Z
David Z

Reputation: 131800

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.

Upvotes: 4

Related Questions