Why when I do this: $ var=$(java -version)
on my bash terminal, var
is always empty? Same thing with $ java -version >> version.txt
nothing is sent to the version.txt file.
The command usually send such information to STDERR, not STDOUT. So in your case you should use commands like:
java -version >>version.txt 2>&1
and
var=$((java -version) 2>&1)
-
1I don't know why you have put the inner brackets round
java -version
: they are unnecessary and invoke a further subshell needlessly. – AFH Dec 12 '18 at 18:30
As Romeo has pointed, java -version
writes in stderr, not in stdout, so you should use:
var=$(java -version 2>&1)
If you want to get the version only and not all the output of the java -version
command, more convinient for scripting for example, you can use something like:
var=$(java -version 2>&1 | awk -F '"' 'NR==1 {print $2}')
Explanation
java -version
prints java version message into stderr2>&1
redirects stderr to stdout|
takes lefthand command output and use it as input for righthand commandawk -F '"' 'NR==1 {print $2}'
is a bit more complicated, but basically it divides the input it receives into parts, allowing you to operate with each part separately (the most knowledgeable probably will throw me to the lions, it is a very bad summary of what is and what awk does).- The character that
awk
takes for the division is specified by the-F
option, in this case it is divided by the character"
- The last part specifies that only the second element (
{print $2}
) from the first line (NR==1
) of the resulting division must be printed.
- The character that
This will output something like 1.8.0_191
.
-
1Thanks for the explanation. I am wondering why Java uses STDERR instead of STDOUT and how do you know this? – akuma8 Dec 13 '18 at 8:53