2

Can someone tell me why this simple command cannot find the output "java version"?

if java -version | grep -q "java version" ; then
  echo "Java installed."
else
  echo "Java NOT installed!"
fi

output from java -version is as follows

java version "1.8.0_77"
Java(TM) SE Runtime Environment (build 1.8.0_77-b03)
Java HotSpot(TM) 64-Bit Server VM (build 25.77-b03, mixed mode)
4
  • 2
    You're not actually checking the output or version, so is there a reason why you don't just use which? Commented Apr 3, 2016 at 17:07
  • 1
    Why grep for the version, when you could just check if the binary itself exists and is executable? Commented Apr 3, 2016 at 17:07
  • 1
    Binary is not in the same place on every machine, wouldn't be sound to test src. Commented Apr 3, 2016 at 17:23
  • Check this out: stackoverflow.com/questions/7334754/… Commented Feb 6, 2017 at 15:34

2 Answers 2

9

java outputs to STDERR. You can use

if java -version 2>&1 >/dev/null | grep -q "java version" ; then

but probably simpler to do something like

if [ -n `which java` ]; then
Sign up to request clarification or add additional context in comments.

1 Comment

I noticed which is not always available from testing this software on multiple machines from the get go to see what is available. Why I was testing the java command. Thanks for the time.
1

If your java is openJDK then you can use following options

java -version 2>&1 >/dev/null | grep "java version\|openjdk version"

or you can make more generic by

java -version 2>&1 >/dev/null | egrep "\S+\s+version"

to get java version

JAVA_VER=$(java -version 2>&1 >/dev/null | egrep "\S+\s+version" | awk '{print $3}' | tr -d '"')

2 Comments

egrep is nonstandard, probably better so do grep -E "\S+\s+version"
java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')

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.