Until the cycle never ends

I am working with bash and I am 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 grep succeeds, and A is 0. What am I missing here? The following is an example output.

 $ ./test.sh 

asdf

 1 

test

 0 

hm ...

 1 
+4
source share
7 answers

You need to use the correct comparison operator. Bash has different operators for comparing integers and strings.

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

You need

 while [ $A -eq 1 ]; do 

See here for more

+8
source

I find the Bash syntax pretty terrible - you tried something like:

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

Perhaps he is trying to redirect 1 to $ A or something strange.

+5
source

Try:

 while [ $A -eq 1 ]; do 
+4
source

Most of the answers focused on an integer / line and spacing issue, which is fine, but your code looks so unified that IMO should be completely reinstalled. Let's say the idea is to process the lines until one line matches the regular expression 'test':

 while read line; do if [[ "$line" =~ test ]] && break # do something with $line done 

Of course, this can be simplified if you use text processing tools such as sed:

 sed -e '/test/,$d' 
+3
source

can you do this. No need to call external grep.

 while true; do read line case "$line" in *test* ) break;; esac done echo $line 
+1
source

You have not tried this

  while [$ A == "1"]
    ....
 done

Edit:. Since Dan mentioned my mistake, I kindly acknowledge my mistake and edited it accordingly - Thanks Dan for the heads ...

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

Sorry! :( Hope this helps, Regards, Tom.

-1
source

All your answers are provided in the Advanced Bash-Scripting guide . This is amazing.

-1
source

Source: https://habr.com/ru/post/1302257/


All Articles