Vel Murugan
Vel Murugan

Reputation: 23

not able to execute ifelse statement inside case statement

I have an if else statement inside 3 parts of a switch statement. I have assigned a command output to a variable based on the output it selects. But it always executes the wildcard *) case and not the other three.

case "$ROLE" in
        server )
                  if [[ ("$a" == 1) && ("$b" == 1) && ("$c" == 1) && ("$d" == 1) && ("$e" == 1) && ("$f" == 1) ]]
                  then
                     echo 'statement'
                  else
                     echo 'statement'
                   fi
                   ;;
       server1 )
                  if [[ ("$a" == 1) && ("$b" == 1) ]]
                  then
                     echo 'statement'
                  else
                     echo "statement"
                  fi
                  ;;
        server2 )
                  if [[("$a" == 1) && ("$b" == 1) && ("$c" == 1) && ("$d" == 1) && ("$g" == 1) && ("$h" == 1)]]
                  then
                      echo 'statement'
                  else
                      echo "statement"
        *) 
         echo "unknown"
esac

Expected behavior is to execute one of the of the 3 cases but currently the wildcard case statement is executed every time.

Upvotes: 0

Views: 172

Answers (1)

Chris Maes
Chris Maes

Reputation: 37742

Seems you were almost there...

case "$ROLE" in
        server ) if [[ ("$a" == 1) && ("$b" == 1) && ("$c" == 1) && ("$d" == 1) && ("$e" == 1) && ("$f" == 1) ]]
                  then
                     echo 'statement'
                  else
                     echo 'statement'
                   fi
                   ;;
       server1 ) if [[ ("$a" == 1) && ("$b" == 1) ]]
                  then
                     echo 'statement'
                  else
                     echo "statement"
                  fi
                  ;;
        server2 ) if [[ ("$a" == 1) && ("$b" == 1) && ("$c" == 1) && ("$d" == 1) && ("$g" == 1) && ("$h" == 1) ]]
                  then
                      echo 'statement'
                  else
                      echo "statement"
                  fi
                  ;;
        *) echo "unknown";;
esac

I just

  • put your if statements straight after your case statements (I thought this necessary but apparently is not @biffen)
  • terminated your final if statement and add ;; otherwise you will have a syntax error
  • and added some spaces

globally your code was ok. I put it in

test.sh and then ran

ROLE=server bash test.sh

getting

statement

Upvotes: 3

Related Questions