简体   繁体   中英

Loop BASH with counter in one line

I wait program finish and print nothing; but this intro in loop:

while [ 0 > 0 ]; do echo 1; done

logically 0 no't is > to 0... why get loop?

How I can get nothing by screen? and program finish fine?

After of my progam "nothing to do":

while [ 0 > 0 ]; do echo 1; done

I like in one line:

q = 0; while [ q < 9 ]; q ++; do echo q; done

it´s possible in one line?

Thanks

q = 0; while [ q < 9 ]; q ++; do echo q; done

Just 5 errors in one line.

  • q=0 may not have white space around the assignment operator
  • q ++ has to be in double round parens
  • q < 9 has to be -lt (less than)
  • in single brackets [ $q -lt 9 ] q needs to be $q
  • the do should follow the while

Possible solution:

q=0; while [[ q -lt 3 ]]; do ((q++)); echo $q; done
1
2
3

echoing values can be done with

echo {1..9}

too, but is not flexible, so you can't use variable expansion inside, like echo {1..$n} . The canonical way of doing initialization, increment and threshold check, is a for loop:

 for (( q=1; q < 4; ++q)); do  echo $q ; done

There is the external program seq, which is not so much recommended, for that reason:

seq 1 3 

First question:

while [ 0 > 0 ]; do echo 1; done

Look for a file 0 where you used file redirection (instead of -gt), like in echo foo > 0.file .

Instead of

while [ 0 -gt 0 ]; do echo 1; done

because it does nothing. It doesn't wait for anything. Either your program is sequential, then it is finished at that point anyhow. Or there is a program/command in the background running, which doesn't care about this anti loop anyhow.

For your second question, use for (( expr1 ; expr2 ; expr3 )) ; do list ; done

Also refer to man bash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM