skip to Main Content

I’m writing a bash script that populates a configuration file and it needs to get the Java version and vendor. I read that the best way to get the Java vendor is to run java -XshowSettings:properties -version. My plan is to use bash regex to get the version and vendor, but storing the command output as a variable is proving trickier than I initially thought.

Here’s a code snippet from my script:

settings_output="$(${java_command} -XshowSettings:properties -version)"
echo "Output: ${settings_output}"

When that runs, I get the following output (ellipses used to abbreviate):

Property settings:
    file.encoding = UTF-8
    ...

openjdk version "17.0.9" 2023-10-17
OpenJDK Runtime Environment (build 17.0.9+9-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 17.0.9+9-Ubuntu-120.04, mixed mode, sharing)
Output: 

But what I expect to get is:

Output: Property settings:
    file.encoding = UTF-8
    ...

openjdk version "17.0.9" 2023-10-17
OpenJDK Runtime Environment (build 17.0.9+9-Ubuntu-120.04)
OpenJDK 64-Bit Server VM (build 17.0.9+9-Ubuntu-120.04, mixed mode, sharing)

I don’t understand:

  1. Why the output of the bash command isn’t being stored in the variable.
  2. Why the output is being displayed upon execution. I haven’t touched local echo at all, but I don’t recall other command substitutions (at least using $(COMMAND) syntax) doing this.

My goal isn’t to print the variable out for the user, but because I’m debugging, I found it necessary.

I’m new to bash (and shell) scripting and this is probably me being a complete bonehead, but hopefully someone can help me out. I figured it was an error with multi-line output, but neither of these two links held an answer to my problem. I’ve even tried declaring an array with each line of the output as elements, but no dice.

Is it obvious to anyone what I’m doing wrong?

2

Answers


  1. You need:

    settings_output="$(${java_command} -XshowSettings:properties -version 2>&1)"
    

    because this java command write the output on STDERR.

    Check: Confused about stdin, stdout and stderr?

    Login or Signup to reply.
  2. The -X options write their output to standard error, so they won’t be mixed in with the regular output of the program. This is in the documentation

    -X
    Prints the help on extra options to the error stream.

    So redirect stderr to stdout so it will be captured.

    settings_output="$(${java_command} -XshowSettings:properties -version 2>&1)"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search