[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: |
Tue, 22 May 2018 11:02:43 +0300 |
User-agent: |
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:52.0) Gecko/20100101 Thunderbird/52.7.0 |
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.
This is mentioned in the manual (apart from a different wording, this is
also what POSIX says):
"""
An OR list has the form
command1 || command2
command2 is executed if, and only if, command1 returns a non-zero exit
status.
The return status of AND and OR lists is the exit status of the last
command executed in the list.
"""
[ https://www.gnu.org/software/bash/manual/html_node/Lists.html ]
using the logical
operators form to obfuscate the code a little,
More than "a little", your second version of the script below looks
horribly unreadable.
the problem seems to be one of the operator
«!» in
a «=~» conditional because when testing this same notation with other
conditions
it does not seem to have an error.
You can hit that in other ways, too, e.g.:
falsy_echo() { echo "$@"; return 1; }
true && falsy_echo yea || echo nay
--
Ilkka Virta / itvirta@iki.fi