Saturday, May 28, 2022

[SOLVED] Why are my nested If conditions not working?

Issue

Using bash to write this script. For some reason my second IF condition is not working. I never get the message "FALSE result" when the condition is false. BTW, I need to nest two more if conditions but wanted to get this first one working. Any suggestions?

if [[ condition == "true" ]] ; then
   echo "TRUE result"

   if [[ condition == "false" ]] ; then
      echo "FALSE result"

   fi
fi

Solution

There are two problems here. The first is that condition is a fixed string, and will never be equal to either "true" or "false". If it's supposed to be a variable, you need to use "$condition" to get its value (the $ is required to get the variable's value, the double-quotes are sometimes needed to avoid weird parsing of the value). So something like if [[ "$condition" == "true" ]] ; then.

The second problem is that since the second if is nested inside the first, it'll never be tested if the first condition is false. That is, if $condition is "false", it'd test whether it's equal to "true", and since it isn't it'll skip everything up to the last fi, and hence never compare it to "false".

What you probably want is an elif (short for "else if") clause instead of a nested if -- that way it'll make the second test only if the first fails, instead of only if it succeeds. Note that an elif clause is not nested, but an extension of the original if statement, so it doesn't take an additional fi to close it. So something like this:

if [[ "$condition" == "true" ]] ; then
   echo "TRUE result"

elif [[ "$condition" == "false" ]] ; then
   echo "FALSE result"

fi

If you're comparing a something against a list of possible strings/patterns, it might be better to use a case statement:

case "$condition" in
   true)
      echo "TRUE result" ;;

   false)
      echo "FALSE result" ;;

   maybe)
      echo "MAYBE result" ;;

   *)
      echo "Unrecognized result" ;;
esac


Answered By - Gordon Davisson
Answer Checked By - Marilyn (WPSolving Volunteer)