Reputation: 2483
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 :
@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 ?
Upvotes: 2
Views: 1149
Reputation: 531708
Note that
if command1; then
command2
else
command3
fi
is not equivalent to command1 && command2 || command3
.
command1
fails, command2
is skipped and command3
runs, as expected.command1
succeeds, and command2
runs and succeeds, command3
is skipped, as expected.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.
Upvotes: 6