Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have a problem concerning storing the output of a command inside a variable within a bash script.
I know in general there are two ways to do this

either

foo=$(bar)
# or
foo=`bar`

but for the Java version query, this doesn't seem to work.

I did:

version=$(java --version)

This doesn't store the value inside the var. It even still prints it, which really shouldn't be the case.

I also tried redirecting output to a file but this also fails.

share|improve this question

2 Answers

 version=$(java -version 2>&1)

The version param only takes one dash, and if you redirect stderr, which is, where the message is written to, you'll get the desired result.

share|improve this answer
thanks a ton, exactly what i was looking for – user1278282 Mar 19 '12 at 12:31

That is because java -version writes to stderr and not stdout. You should use:

version=$(java -version 2>&1)

In order to redirect stderr to stdout.

You can see it by running the following 2 commands:

java -version > /dev/null

java -version 2> /dev/null
share|improve this answer
thank you for your insight, it seems top also prints the version too stderr – user1278282 Mar 19 '12 at 12:31

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.