Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > gnu.bash.bug > #14127

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

From Ilkka Virta <itvirta@iki.fi>
Newsgroups gnu.bash.bug
Subject Re: Conditions with logical operators and nested groups execute "if" and "else"
Date 2018-05-22 11:02 +0300
Message-ID <mailman.218.1526976186.1292.bug-bash@gnu.org> (permalink)
References <CAM4RgKgOACdJtjBFpKMhfoXvbSwun=84pPdADNaJVKcd-Z5GFg@mail.gmail.com>

Show all headers | View raw


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

Back to gnu.bash.bug | Previous | Next | Find similar | Unroll thread


Thread

Re: Conditions with logical operators and nested groups execute "if" and "else" Ilkka Virta <itvirta@iki.fi> - 2018-05-22 11:02 +0300

csiph-web