Syntax for a single-line Bash infinite while loop

前端 未结 13 1381
长情又很酷
长情又很酷 2020-11-29 14:18

I am having trouble coming up with the right combination of semicolons and/or braces. I\'d like to do this, but as a one-liner from the command line:

while [         


        
相关标签:
13条回答
  • 2020-11-29 14:51

    If you want the while loop to stop after some condition, and your foo command returns non-zero when this condition is met then you can get the loop to break like this:

    while foo; do echo 'sleeping...'; sleep 5; done;
    

    For example, if the foo command is deleting things in batches, and it returns 1 when there is nothing left to delete.

    This works well if you have a custom script that needs to run a command many times until some condition. You write the script to exit with 1 when the condition is met and exit with 0 when it should be run again.

    For example, say you have a python script batch_update.py which updates 100 rows in a database and returns 0 if there are more to update and 1 if there are no more. The the following command will allow you to update rows 100 at a time with sleeping for 5 seconds between updates:

    while batch_update.py; do echo 'sleeping...'; sleep 5; done;
    
    0 讨论(0)
  • 2020-11-29 14:54

    Using while:

    while true; do echo 'while'; sleep 2s; done
    

    Using for Loop:

    for ((;;)); do echo 'forloop'; sleep 2; done
    

    Using Recursion, (a little bit different than above, keyboard interrupt won't stop it)

    list(){ echo 'recursion'; sleep 2; list; } && list;
    
    0 讨论(0)
  • 2020-11-29 14:56

    A very simple infinite loop.. :)

    while true ; do continue ; done
    

    Fr your question it would be:

    while true; do foo ; sleep 2 ; done
    
    0 讨论(0)
  • 2020-11-29 15:02
    while true; do foo; sleep 2; done
    

    By the way, if you type it as a multiline (as you are showing) at the command prompt and then call the history with arrow up, you will get it on a single line, correctly punctuated.

    $ while true
    > do
    >    echo "hello"
    >    sleep 2
    > done
    hello
    hello
    hello
    ^C
    $ <arrow up> while true; do    echo "hello";    sleep 2; done
    
    0 讨论(0)
  • 2020-11-29 15:06

    Colon is always "true":

    while :; do foo; sleep 2; done
    
    0 讨论(0)
  • 2020-11-29 15:09

    It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

    while sleep 2; do echo thinking; done
    
    0 讨论(0)
提交回复
热议问题