user2975559 user2975559 - 6 months ago 8
Bash Question

AND, OR conditions in if statement

i have the following code

elif [ $text2 == 'LANDING' ] && [ "$text4" == 'FAIL' ] || [ "$text4" == '' ]; then


the condition is that text2 should be landing and text4 can either be fail or null.
How to evaluate the above command.

Please help if Im doing any wrong
Thanks in advance

Answer

You need to group them explicitly:

elif  [ "$text2" = 'LANDING' ] &&
      { [ "$text4" = 'FAIL' ] || [ "$text4" = '' ]; }; then

Your attempt would succeed either of the following two conditions held:

  1. text2 was LANDING and text4 was FAIL
  2. text4 was empty or unset.

Since && and || have the same precedence, you could (perhaps surprisingly) write it without grouping:

elif [ "$text4" = '' ] || [ "$text4" = FAIL ] && [ $text2 == 'LANDING' ]; then

If you are using bash, you can use the [[ ... ]] command instead of [ ... ]. The grouping is required; the operators inside [[ ... ]] do have the precedences you would expect from other languages (that is, a || b && c is a || (b && c), not (a || b) && c).

elif [[ $text2 == 'LANDING' && ( "$text4" == 'FAIL' || "$text4" == '') ]]; then
Comments