0

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.

2 Answers 2

3

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)
1
  • 1
    I 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, 2018 at 18:30
4

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

  1. java -version prints java version message into stderr
  2. 2>&1redirects stderr to stdout
  3. | takes lefthand command output and use it as input for righthand command
  4. awk -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.

This will output something like 1.8.0_191.

1
  • 1
    Thanks for the explanation. I am wondering why Java uses STDERR instead of STDOUT and how do you know this?
    – akuma8
    Dec 13, 2018 at 8:53

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .