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


Groups > gnu.bash.bug > #14127 > unrolled thread

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

Started byIlkka Virta <itvirta@iki.fi>
First post2018-05-22 11:02 +0300
Last post2018-05-22 11:02 +0300
Articles 1 — 1 participant

Back to article view | Back to gnu.bash.bug

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

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

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

FromIlkka Virta <itvirta@iki.fi>
Date2018-05-22 11:02 +0300
SubjectRe: Conditions with logical operators and nested groups execute "if" and "else"
Message-ID<mailman.218.1526976186.1292.bug-bash@gnu.org>
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

[toc] | [standalone]


Back to top | Article view | gnu.bash.bug


csiph-web