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.

6
  • what do you need the version for? Commented Jul 18, 2022 at 8:35
  • There may be useful information about that in stackoverflow.com/q/7334754/10871900 (although that's mainly about the major version) Commented Jul 18, 2022 at 8: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. Commented Jul 18, 2022 at 8:37
  • do you need to extract the version or is it enough to know it is that version? Commented Jul 18, 2022 at 8:41
  • @criztovyl It is enough to know if that is the version Commented Jul 18, 2022 at 8:44

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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".
Argh, true! I'll add -F
1
$ IFS='"_' read -r _ ver _ < <(java -version 2>&1)
$ echo "$ver"
1.8.0

Comments

0

You can try this one

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

output

openjdk 8.0

Comments

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}'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.