1

I'm automating some things via bash and one of the things I wish to do is only execute a certain command if a condition is false.

I have written this little script to check the existence of java on a machine and then, if it doesn't exist, install java on the machine:

#!/bin/bash

java_path=$(which java) 
if [ "$java_path" = "/usr/bin/java" ]; then
    printf "\nJava Installed, version:\n"
    java -version
else
    printf "\nJava Not Installed, Installing...\n"
    #sudo amazon-linux-extras install java-openjdk11
    java -version
fi

My problem is that the code always goes down the else path, even though when I execute which java via commandline, I get usr/bin/java

What am I doing wrong?

Prithvi Boinpally
  • 427
  • 1
  • 9
  • 23

2 Answers2

2

The exit status of which can be used in the if-else statement, no need to save the output.

if which java > /dev/null 2>&1; then
    java -version
else
    echo "Java not installed"
fi
LMC
  • 10,453
  • 2
  • 27
  • 52
1

You can use this:

#!/bin/bash
#
if [[ $(which java) == "/usr/bin/java" ]]
then
    printf "\nJava Installed, version:\n"
    java -version
else
    printf "\nJava Not Installed, Installing...\n"
fi

Since you assume java will be in /usr/bin, you consider only the installation via the official package. You could check if the package is installed instead.

To cover all cases, you could:

  • check if the package is installed.
  • check if which java returns something.
  • run a find to see if it is somewhere else on the system.
Nic3500
  • 8,144
  • 10
  • 29
  • 40