Home > Blockchain >  Why are my nested If conditions not working?
Why are my nested If conditions not working?

Time:05-20

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

CodePudding user response:

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

CodePudding user response:

read -p "Enter hostname(s): " HOSTS

for host in $HOSTS
do
   echo "Test ssh-port on $host"
   nc -zv -w 2 $host 22
   if [ $? -ne 0 ]; then
      echo "$host is not reachable.. See message above. Check hostname/ssh-deamon/firewall"
      continue
   fi
   if [ "$host" = "host1" -o "$host" = "host2" ] ; then
        message=$(ssh -q -t adminuser@$host "/usr/bin/sudo systemctl is-active sc4s.service")
        echo "The SC4S service on $host is $message"
        [ "$message" = "inactive" ] && echo "Please run the startsplunk script to restart the service on $host"
   fi
done
  • Related