sh AND and OR in one command
This will work:
if [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] || [ "$bool1" == true ] ; then echo "conditions met - running code ..."; fi;
Or surround with { ;}
for readability and easy to maintain in future.
if { [ "$string1" != "$string2" ] && [ "$string3" != "$string4" ] ;} || [ "$bool1" == true ] ; then echo "conditions met - running code ..."; fi;
Reference:
- No such thing boolean variable. See this.
{ ;}
, See this.&&
has higher precedence than||
only in (()) and [[]]
&&
higher precedence only happen in [[ ]]
is proven as follows. Assume bool1=true
.
With [[ ]]
:
bool1=true
if [[ "$bool1" == true || "$bool1" == true && "$bool1" != true ]]; then echo 7; fi #1 # Print 7, due to && higher precedence than ||
if [[ "$bool1" == true ]] || { "$bool1" == true && "$bool1" != true ;}; then echo 7; fi # Same as #1
if { "$bool1" == true ]] || "$bool1" == true ;} && [[ "$bool1" != true ]] ; then echo 7; fi # NOT same as #1
if [[ "$bool1" != true && "$bool1" == true || "$bool1" == true ]]; then echo 7; fi # Same result as #1, proved that #1 not caused by right-to-left factor, or else will not print 7 here
With [ ]
:
bool1=true
if [ "$bool1" == true ] || [ "$bool1" == true ] && [ "$bool1" != true ]; then echo 7; fi #1, no output, due to && IS NOT higher precedence than ||
if [ "$bool1" == true ] || { [ "$bool1" == true ] && [ "$bool1" != true ] ;}; then echo 7; fi # NOT same as #1
if { [ "$bool1" == true ] || [ "$bool1" == true ] ;} && [ "$bool1" != true ]; then echo 7; fi # Same as #1
if [ "$bool1" != true ] && [ "$bool1" == true ] || [ "$bool1" == true ]; then echo 7; fi # Proved that #1 not caused by || higher precedence than &&, or else will not print 7 here, instead #1 is only left-to-right evaluation