Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Java Installed with Bash

Tags:

java

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)
like image 714
WASasquatch Avatar asked Jul 25 '26 18:07

WASasquatch


2 Answers

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
like image 197
Reimeus Avatar answered Jul 28 '26 07:07

Reimeus


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 '"')
like image 41
ChitreshG Avatar answered Jul 28 '26 08:07

ChitreshG



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!