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)
WASasquatch
  • 611
  • 2
  • 8
  • 23

2 Answers2

8

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
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 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. – WASasquatch Apr 03 '16 at 17:25
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 '"')
chitresh
  • 316
  • 4
  • 11