bug-bash
[Top][All Lists]
Advanced

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

Re: important bug


From: Greg Wooledge
Subject: Re: important bug
Date: Wed, 28 Mar 2018 16:36:58 -0400
User-agent: NeoMutt/20170113 (1.7.2)

On Wed, Mar 28, 2018 at 08:22:16PM +0200, Klaus Bartels wrote:
> If you execute the following script the result is wrong. It is self
> explaining:
> -------------------------------
> #
> # GNU bash, version 4.4.12(1)-release (x86_64-slackware-linux-gnu)
> # Linux ... 4.9.31 #1 SMP Wed Jun 7 14:57:36 CDT 2017 x86_64 Intel(R)
> Core(TM) i5-7400 CPU @ 3.00GHz GenuineIntel GNU/Linux
> #
> test a = a && {
>   echo this line should be displayed
>   test a = b && {
>     echo this line should also not displayed, but creates the error
>     }
>     # echo uncomment this line and all works fine again
>   } || {
>   echo this line should never be displayed
>   }
> #
> ------------------------------
> If you uncomment the line in the middle, the script works correct.
> I hope, it helps

First of all, your indentation is bad.  The way the curly braces fail
to line up hides the intent of the program.

Second, the use of && and || together is a really bad idea, as explained
here: <https://mywiki.wooledge.org/BashPitfalls#pf22>

Here's what you have:

wooledg:~$ true && { echo 1; false && { echo 2; }; } || { echo 3; }
1
3

Here's what you actually (seem to!) want:

wooledg:~$ if true; then echo 1; if false; then echo 2; fi; else echo 3; fi
1

Now, your question is "why does inserting another echo change the
result of my program?"  The answer: at the time the || in your program
is evaluated, the current exit status is that of "false" (or in your
original, "test a = b").  The exit status is still set to 1, so the
"echo 3" gets executed.

But by adding another echo statement (with an exit status of 0), by
the time the program gets to the || the current exit status is now 0,
so the "echo 3" is NOT executed.

The whole problem is caused by the chaining of && and || together.
Don't do that.  It doesn't do what you think it does.  It is NOT a
synonym for if; then; else; fi.

Please use the formal if; then; else; fi instead.  And fix your
indentation so that the logic is understandable.



reply via email to

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