bug-bash
[Top][All Lists]
Advanced

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

Re: while clause with two conditions does not execute when continue is u


From: Dale R. Worley
Subject: Re: while clause with two conditions does not execute when continue is used
Date: Wed, 21 Oct 2020 22:11:10 -0400

rrd@beelaertsict.nl writes:
> #!/bin/bash
> # test error in while clause
> #
> set -x
> up () {
>     i=$(($i+1))
>     [ $i -eq 5 ] && j=$(($j+1)) && i=0
> }
> i=0
> j=0
> # while loop should end when i=4 and j=2
> while [ $i -ne 4 -o $j -ne 2 ]
> do
>     if [ $i -eq 3 ]
>     then
>       up && continue
>     fi
>     echo i=$i j=$j
>     up
> done

It would have helped if your example wasn't so very complicated.  I
suspect that you are expecting some of the "&&" to act like ";" that is,
the command following will always be executed.  If you expect that, you
should write the code to make that explicit.  In addition, you didn't
place echo's in places that would be quite informative, especially
around the "continue" and at the bottom of the loop.

If I add some echo's like this:

    #!/bin/bash
    # test error in while clause
    #
    set -x
    up () {
        i=$(($i+1))
        [ $i -eq 5 ] && j=$(($j+1)) && i=0
    }
    i=0
    j=0
    # while loop should end when i=4 and j=2
    while [ $i -ne 4 -o $j -ne 2 ]
    do
        echo Testing i == 3
        if [ $i -eq 3 ]
        then
            echo Continuing
            up && continue
            echo continue not executed
        fi
        echo i=$i j=$j
        up
        echo At bottom i=$i j=$j
    done

and then run it, the relevant segment of the output is

    + echo At bottom i=3 j=2
    At bottom i=3 j=2
    + '[' 3 -ne 4 -o 2 -ne 2 ']'
    + echo Testing i == 3
    Testing i == 3
    + '[' 3 -eq 3 ']'
    + echo Continuing
    Continuing
    + up
    + i=4
    + '[' 4 -eq 5 ']'
    + echo continue not executed
    continue not executed
    + echo i=4 j=2
    i=4 j=2
    + up
    + i=5
    + '[' 5 -eq 5 ']'
    + j=3
    + i=0
    + echo At bottom i=0 j=3
    At bottom i=0 j=3

This makes it clear what is happening:  when i == 3, the "if" is entered
and the "up" is executed.  But the "up" returns status 1, and so the
"continue" is not executed.  Execution continues in the block to the
second "up", which increments i and then rolls over to increment j.  The
exit condition is never met.

Dale



reply via email to

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