Bourne Shell Conditional Operators

conditional-statements, sh

Solution

`||` and `&&` have equal precedence, unlike in languages where the logical AND operator binds more tightly than the logical OR. This means your code as written is equivalent to

if { [ "$a" -eq 1 ] || [ "$b" -gt 0 ]; } && [ "$c" != "0 kB/s" ] ; then
  echo "a = 1 or b > 0 and c <> 0: true"
else
  echo "a = 1 or b > 0 and c <> 0: false"
fi

rather than the expected

if [ "$a" -eq 1 ] || { [ "$b" -gt 0 ] && [ "$c" != "0 kB/s" ]; } ; then
  echo "a = 1 or b > 0 and c <> 0: true"
else
  echo "a = 1 or b > 0 and c <> 0: false"
fi

Problem

I am having a lot of fun playing with Bourne Shell, but I am facing a quite cryptic situation regarding conditions: ``` #! /bin/sh a=1 b=2 c="0 kB/s" if [ "$a" -eq 1 ] ; then echo "a = 1: true" ; else echo "a = 1: false" ; fi if [ "$b" -gt 0 ] ; then echo "b > 0: true" ; else echo "b > 0: false" ; fi if [ "$c" != "0 kB/s" ] ; then echo "c <> 0: true" ; else echo "c <> 0: false" ; fi if [ "$a" -eq 1 ] || [ "$b" -gt 0 ] ; then echo "a = 1 or b > 0: true" ; else echo "a = 1 or b > 0: false" ; fi if [ "$a" -eq 1 ] || [ "$b" -gt 0 ] && [ "$c" != "0 kB/s" ] ; then echo "a = 1 or b > 0 and c <> 0: true" ; else echo "a = 1 or b > 0 and c <> 0: false" ; fi if [ true ] || [ true ] && [ false ] ; then echo "true or true and false: true" ; else echo "true or true and false: false" ; fi ``` gives me the following result: ``` a = 1: true b > 0: true c <> 0: false a = 1 or b > 0: true a = 1 or b > 0 and c <> 0: false true or true and false: true ``` Short question: why don't I get `a = 1 or b > 0 and c <> 0: true`? Thanks a lot for your help ...

Original source