Home > other >  Get the Java version in specific format using bash
Get the Java version in specific format using bash

Time:07-18

My Java version is:

openjdk version "1.8.0_312"
OpenJDK Runtime Environment (build 1.8.0_312-b07)
OpenJDK 64-Bit Server VM (build 25.312-b07, mixed mode)

How can I get the Java version in below format using bash script: 1.8.0

I tried multiple options like java -version 2>&1 | head -n 1 | cut -d'"' -f2, but I'm unable to get the desired output.

CodePudding user response:

To check for a string (your expected version), you can use grep:

if java -version 2>&1 | head -n 1 | grep --fixed-strings '"1.8.0'
then echo expected version
else echo unexpected version
fi

Note the --fixed-strings (short -F), otherwise grep treats . as a RegEx and it will match any character. Thx Gorodon for pointing that out! I also added the leading " quote so it will not match 11.8.0.

CodePudding user response:

You can try this one

java --version | head -n1 |cut -d " " -f1,2

output

openjdk 8.0

CodePudding user response:

You can use grep (or egrep) to print matching patterns:

java --version | head -n 1 | grep -Po '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'     
java --version | head -n 1 | egrep -o '[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}'

CodePudding user response:

$ IFS='"_' read -r _ ver _ < <(java -version 2>&1)
$ echo "$ver"
1.8.0
  • Related