Home > database >  Bash if-statement gets stuck
Bash if-statement gets stuck

Time:12-07

I get this loop but for some reason, the if conditional get stucks. The while loop works perfectly.

The inputs are those (the x, y, z are word that changes everytime you execute the script):

name0="Car name X"

name1="Car name Y"

name2="Car name Z"
        echo $name0
        echo $name1
        echo $name2
while [ $ext -eq 0 ]
do
    if [ "$name1" = "$name2" ]
    then
    ext=1
        name1="`shuf -n 1 cars.csv | cut -d";" -f1`"
        name1c=`echo $name1 | cut -d" " -f1`
        ext=1
    else
        :
    fi
done

EDIT to loop:

while [ $ext -eq 0 ]
do
    if [ "$name1" != "$name2" ]
    then
        :
    else

        name1="`shuf -n 1 cars.csv | cut -d";" -f1`"
        name1c=`echo $name1 | cut -d" " -f1`
        ext=1
    fi
done

It outputs somethink like this (without #):

Car name 1

Car name 2

Car name 3
#

And gets stuck in the #, I can enter more text but it does nothing.

CodePudding user response:

Your code runs in an infinite loop: since name1 and name2 are not equal in the beginning, you will not enter the then block of the if-then-else. And thus, exit will never get the value 1.

On a side note: since exit is a shell builtin, you should rather prefer a different name for that variable to avoid confusion.

  • Related