WASasquatch
WASasquatch

Reputation: 629

Check if Java Installed with Bash

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)

Upvotes: 2

Views: 11310

Answers (2)

chitresh
chitresh

Reputation: 346

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 '"')

Upvotes: 1

Reimeus
Reimeus

Reputation: 159754

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

Upvotes: 9

Related Questions