0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user15566016
  • 33
  • 10
  • what do you need the version for? – criztovyl Jul 18 '22 at 08:35
  • There may be useful information about that in https://stackoverflow.com/q/7334754/10871900 (although that's mainly about the major version) – dan1st Jul 18 '22 at 08:36
  • @criztovyl I want to check if exact matching version i.e "1.8.0" exists on my machine or not. I referred many stackoverflow content however unable to get the desired result. – user15566016 Jul 18 '22 at 08:37
  • do you need to extract the version or is it enough to know it is that version? – criztovyl Jul 18 '22 at 08:41
  • @criztovyl It is enough to know if that is the version – user15566016 Jul 18 '22 at 08:44
  • You are already close: The command you posted here returns you `1.8.0_312`. Store this string into a variable and remove everything starting with the underscore character from the variable. See the section titled _Parameter Expansion_ in the bash man page. – user1934428 Jul 18 '22 at 08:44

4 Answers4

3

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.

criztovyl
  • 761
  • 5
  • 21
  • 3
    `grep` treats its argument as a regular expression, meaning that "." will match any character. It also only looks for a match *somewhere* in a line, meaning it'll match substrings. These mean it could match things that're radically different from what you'd expect, like "11.8.0" or "1.850.5". – Gordon Davisson Jul 18 '22 at 09:58
  • Argh, true! I'll add `-F` – criztovyl Jul 18 '22 at 10:08
1
$ IFS='"_' read -r _ ver _ < <(java -version 2>&1)
$ echo "$ver"
1.8.0
Ed Morton
  • 188,023
  • 17
  • 78
  • 185
0

You can try this one

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

output

openjdk 8.0
0xh3xa
  • 4,801
  • 2
  • 14
  • 28
0

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}'
sinkmanu
  • 1,034
  • 1
  • 12
  • 24