Home > Software design >  Bash shell logical Not with "!". What can't I see with this script?
Bash shell logical Not with "!". What can't I see with this script?

Time:11-22

I use the following and it loops continually. Why doesn't it stop when $i is below 10?

Thanks.

#! /bin/bash
#
        n=10
        nn=20
#
        for (( i=$(($n $nn)) ; ! i<=10 ; i -=2 ))
        do
                echo $i
        sleep 1
                if [ $i -le 0 ]
        then
                 exit 99
        fi
        done
#
        echo "Done with the value of i which started at $(($n $nn)) is exited with i=$i"

CodePudding user response:

You should simply use >:

for (( i=$(($n $nn)) ; i > 10 ; i -=2 ))

Or try with parenthesis:

for (( i=$(($n $nn)) ; !( i <= 10 ) ; i -=2 ))

Edited: I misread the doc (https://www.gnu.org/software/bash/manual/html_node/Shell-Arithmetic.html): logical and bitwise negation should work, but I suppose the <= has less priority than !.

CodePudding user response:

The reason is because ! i is always less than ten. ! does take precedence over comparison operators. The order of precedence for operators is listed in man bash > ARITHMETIC EVALUATION.

! i <= 10 tests if the logical negation of i is less than or equal to ten. For all values of i except zero, where it's one, the logical negation of i is zero. So it will always be true.

  •  Tags:  
  • bash
  • Related