-2

So I want to have an automated Bash script that checks for java and if its not there or super old version (lower than 7) it installs it.

I have something that works, but it runs all part of the bash script yielding odd results.

Code:

#!/bin/bash

# This file will call versions and install if necessary

version_call_java = $(java -version)
java_call_len = ${#version_call_java}
if [[ $version_call_java == *"not found"* ]]; then
  echo "It's not there!"
  sudo apt-get install java
  echo "Installing Java"
elif [[ $version_call_java == *"version*" ]]
  echo "Its there!"
fi
date

The results of the code:

Results

Lines 5, 6, and 13 shouldn't run.

Also is my logic correct? I look for the words "not found" for if the machine doesn't have java. Maybe "recognized" is better but not sure if there is a boolean for if a software program exists or not on a machine.

Dasman
  • 317
  • 4
  • 19
  • 3
    No spaces around 'assignments'! The shell is a very space-sensitive language in many ways. See also https://shellcheck.net/ – Jonathan Leffler Jan 04 '18 at 18:19
  • 4
    If you're looking to fix your script, try [shellcheck](http://shellcheck.net). – that other guy Jan 04 '18 at 18:19
  • @CharlesDuffy Your duplicate nomination comment was removed when I affirmed it, and now I can't reconstruct the other things it said -- sorry about that! – tripleee Jan 05 '18 at 03:13

1 Answers1

1

Here is a working version of your script:

#!/bin/bash

# This file will call versions and install if necessary

version_call_java=$(java -version)
java_call_len=${#version_call_java}
if [[ $version_call_java == *"not found"* ]]; then
  echo "It's not there!"
  sudo apt-get install java
  echo "Installing Java"
elif [[ $version_call_java == *"version"* ]]; then
  echo "Its there!"
fi
date

There were 3 issues.

1) version_call_java = $(java -version) <<= no need for spaces when assigning values to variables.

2) You need to add then after the elseif condition.

elif [[ $version_call_java == *"version"* ]]; then

3) *"version*" should be *"version"*

z atef
  • 7,138
  • 3
  • 55
  • 50
  • True. The logic seems to not work for me however. The script attempts to install java. – Dasman Jan 04 '18 at 18:36
  • That maybe because of "no found". I do not think not found is what you will get when java is not installed. You may want to find the exact message and replace it with "no found" – z atef Jan 04 '18 at 18:43
  • @zee, inasfar as the question's scope crosses multiple distinct problems, it's generally better to either ask the OP to narrow scope to isolate a single specific issue or simply vote to close. See [How to Answer](https://stackoverflow.com/help/how-to-answer), particularly the section "Answer well-asked questions". – Charles Duffy Jan 04 '18 at 18:56
  • Thanks for the heads up @CharlesDuffy, will do.... – z atef Jan 04 '18 at 19:11