Bash script save command output to variable

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

or

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

but for requesting a Java version, this does not seem to work.

I did:

 version=$(java --version) 

This does not save the value inside var. He even prints it, which really shouldn't be.

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

+44
variables bash store
Mar 19 '12 at 10:05
source share
2 answers
  version=$(java -version 2>&1) 

The version parameter accepts only one dash, and if you redirect stderr, that is, where the message is written, you will get the desired result.

As a side element, the use of two hyphens is an unofficial standard for Unix-like systems, but since Java tries to be almost identical on different platforms, it violates Unix / Linux expectations and behaves the same in this regard as it does on Windows, and as I suspect on Mac OS.

+53
Mar 19 '12 at 10:09
source share

This is because java -version written to stderr , not stdout . You should use:

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

To redirect stderr to stdout .

You can see it by running the following 2 commands:

 java -version > /dev/null java -version 2> /dev/null 
+14
Mar 19 '12 at 10:15
source share



All Articles