Question

I am trying to establish the equivalence of using Logical && and || operators to an 'If then else fi' condition and I wanted to verify if that understanding's correct. Consider this if condition , relevant to mine

if ( flag="$value" ) then 
function1 ( p1) 
rc=$?
    if ( "$rc"=0 ) then 
    function2 ( p2)
    fi
elif (flag="$value2" ) then
function1 ( p1) 
rc=$?
    if ( "$rc"=0 ) then 
    function2 ( p2)
    fi
else 
echo "Msg"
fi

written in terms of logical && and || as

 ( ( [ flag = "$value" ] && function1 (p1) ) && function2 (p2) ) || 
   ( ( [ flag = "$value2" ] && function1 (p2) ) && function2 (p2)) || 
    echo "message" 

My Q's are :

  • Can the above approach always be used. What are the caveats and things to "watch out" for
  • There was some talk elsewhere of () brackets spinning of a new shell whose variables are'nt available to the parent. I wanted to see how I can group these operators to indicate precedence, if its not those () brackets.

@Chepner. Thx for the clarification. So in a case statement that looks like this

optf=false
opte=false
optp=false

case $opt in

  p ) ...
     (( $opte || $optf ) && [ -n "$s1" ] ) && echo "error message" 

The above can be rewritten as

 {{ $opte || $optf } ; && [ -n "$s1" ] ; } && echo "error message" 

and it would translate this logic thus : when you encounter the p option , check if opte or optf are true. If either is true and there is a value for s1 , then throw in the error message. Would that be the case , or there are still some holes to be plugged. Gotcha- I was unmindful of the ";" . With { } ; - I should be able to club my operators , way I want ?

Was it helpful?

Solution

Note that

if command1; then
    command2
else
    command3
fi

is not equivalent to command1 && command2 || command3.

  • If command1 fails, command2 is skipped and command3 runs, as expected.
  • If command1 succeeds, and command2 runs and succeeds, command3 is skipped, as expected.
  • If command1 succeeds, and command2 runs and fails, command3 is run, which differs from the if statement.

You would need to use something like:

command1 && { command2; true; } || command3

which would force the right-hand operand to && to succeed, regardless of the success of command2, so that command3 is never run when command1 succeeds.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top