1

I am new to bash scripting, I wish to have if condition ladder
I am reading a string, based on which I want the correct if condition to be processed.

The logic is as follows -

If the string contains a substring -deploy, only then allow it to enter the if condition ladder.

If the string contains both -functions and -layer substrings, then only my 1st if condition block needs to be called,

elsif check for -functions substring

elsif check for -layer substring

I've come up with the following code so far-

commitMessage='[STABLE] -deploy -functions [one,two] -layer some commit message'

if [[ ($commitMessage == *"deploy"* ) && ($commitMessage == *"functions"*) || ($commitMessage == *"layer"*) ]] ; then
  if [[ ($commitMessage == *"functions"*) && ($commitMessage == *"layer"*) ]] ; then
    echo 'functions and layer'
  fi

  elsif [[ $commitMessage == *"functions"* ]] ; then
    echo 'functions only'
  fi

  elsif [[ $commitMessage == *"layer"* ]] ; then
    echo 'layer only'
  fi
fi

I am getting a syntax error for elsif -

syntax error near unexpected token `elif'

I am referring this, but don't understand what I'm doing wrong -
Bash IF : multiple conditions

Dev1ce
  • 5,390
  • 17
  • 90
  • 150
  • The error says `elif`, but the code in your question uses `elsif` (with an **s**). Are you using `elif` throughout? Also, shellcheck.net may be able to point out the issue. – cxw Jun 19 '19 at 03:28
  • 1
    Assuming your original code says `elif` (as in your error message) then the main error is the `fi`s that you have before the `elif`s. Just remove them. – ooga Jun 19 '19 at 03:32

2 Answers2

1

The problem with your code is the usage of incorrect if clause terminators inside the nested if clause and using incorrect keyword for else if branching i.e. elif instead of elsif (the latter is used in Python). See https://ideone.com/1sw0q5

But a case statement would be rather more readable in this case which could be written as

if [[ $commitMessage == *"-deploy"* ]]; then
     case "$commitMessage" in
         *"-functions"*"-layer"*) echo 'functions and layer' ;;
         *"-functions"*) echo 'functions only' ;;
         *"-layer"*) echo 'layer only' ;;
         *) echo 'no match'
     esac
fi
Inian
  • 80,270
  • 14
  • 142
  • 161
  • 1
    Thanks @Inian using switch was a much cleaner approach than the messy if else nesting for my case – Dev1ce Jun 19 '19 at 03:55
0

I believe you should not be using elsif, instead you should be using elif. You can refer the below documentation. https://tecadmin.net/tutorial/bash-scripting/bash-if-else-statement/

Harijith R
  • 329
  • 2
  • 8