Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop never ends

I'm working with bash and I'm trying to do something like this:

A=1
while [ $A=1 ]; do
    read line
    echo $line | grep test >/dev/null   
    A=$?
    echo $A
done 

This script never ends even when the grep finishes successfully and A is set to 0. What am I missing here? Below is a sample of the output.

$ ./test.sh

asdf

1

test

0

hm...

1
like image 362
Shawn J. Goff Avatar asked Dec 01 '22 06:12

Shawn J. Goff


2 Answers

You need to use the correct comparison operator. Bash has different operators for integer and string comparison.

In addition, you need the correct spacing in the comparison expression.

You need

while [ $A -eq 1 ]; do

See here for more

like image 163
Dancrumb Avatar answered Dec 04 '22 05:12

Dancrumb


I find Bash's syntax pretty awful - have you tried something like:

while [ $A -eq 1 ] ... ?

It may be trying to re-assign 1 to $A or something strange like that.

like image 45
Andy Shellam Avatar answered Dec 04 '22 05:12

Andy Shellam