bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Conditions with logical operators and nested groups execute "if" and


From: Ilkka Virta
Subject: Re: Conditions with logical operators and nested groups execute "if" and "else"
Date: Thu, 31 May 2018 15:59:54 +0300
User-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:52.0) Gecko/20100101 Thunderbird/52.8.0

On 31.5. 02:20, L A Walsh wrote:


Ilkka Virta wrote:
On 22.5. 00:17, Uriel wrote:
As you know, a conditional is of the type:
if [[ EXPRESSION ]]; then TRUE CONDITION; else ALTERNATIVE RESULT; fi

Or with logical operators and groups:
[[ EXPRESSION ]] && { TRUE CONDITION; } || { ALTERNATIVE RESULT; }

No, those are not the same. In the latter, the `||` operator checks the last exit status. That may be the one from the "expression" part, or the one from the "true condition" part, depending on which one was the previous to run.

So, the `condition && if_true || if_false` shorthand only works as an if-then-else as long as `if_true` never fails.
---
That doesn't seem to be what bash does:

for cond in "0 0" "0 1" "1 0" "1 1" ; do
x=${cond% *} y=${cond#* }
[[ 1 == $x ]] && { [[ 1 == $y ]]; } || { echo "for (x=$x, y=$y) doAlt" ; } done
for (x=0, y=0) doAlt
for (x=0, y=1) doAlt
for (x=1, y=0) doAlt

I.e. doAlt is done if either or both of the expressions
around the '&&' are not true.

If both conditions around '&&' are true, the 'or'(then) clause isn't done.

If the 1st expression is false, it would skip directly to
the '||' and would execute the 3rd clause.
If the 1st expresion is true then it does the 2nd clause.
If that is false, the '||' clause is done, but if true,
the '||' clause would not be done.

In other words, || checks the exit status of the last command that was executed.

And as your example shows, 'cmd1 && cmd2 || cmd3' is not the same as
'if cmd1; then cmd2; else cmd3' which was the comparison this thread started with.


--
Ilkka Virta / address@hidden



reply via email to

[Prev in Thread] Current Thread [Next in Thread]