Syntax for a single-line Bash infinite while loop

前端 未结 13 1380
长情又很酷
长情又很酷 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:45

    You can try this too WARNING: this you should not do but since the question is asking for infinite loop with no end...this is how you could do it.

    while [[ 0 -ne 1 ]]; do echo "it's looping";   sleep 2; done
    
    0 讨论(0)
  • 2020-11-29 14:46

    You can also make use of until command:

    until ((0)); do foo; sleep 2; done
    

    Note that in contrast to while, until would execute the commands inside the loop as long as the test condition has an exit status which is not zero.


    Using a while loop:

    while read i; do foo; sleep 2; done < /dev/urandom
    

    Using a for loop:

    for ((;;)); do foo; sleep 2; done
    

    Another way using until:

    until [ ]; do foo; sleep 2; done
    
    0 讨论(0)
  • 2020-11-29 14:48

    I like to use the semicolons only for the WHILE statement, and the && operator to make the loop do more than one thing...

    So I always do it like this

    while true ; do echo Launching Spaceship into orbit && sleep 5s && /usr/bin/launch-mechanism && echo Launching in T-5 && sleep 1s && echo T-4 && sleep 1s && echo T-3 && sleep 1s && echo T-2 && sleep 1s && echo T-1 && sleep 1s && echo liftoff ; done
    
    0 讨论(0)
  • 2020-11-29 14:48

    For simple process watching use watch instead

    0 讨论(0)
  • 2020-11-29 14:49

    If I can give two practical examples (with a bit of "emotion").

    This writes the name of all files ended with ".jpg" in the folder "img":

    for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done
    

    This deletes them:

    for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done
    

    Just trying to contribute.

    0 讨论(0)
  • 2020-11-29 14:50

    You can use semicolons to separate statements:

    $ while [ 1 ]; do foo; sleep 2; done
    
    0 讨论(0)
提交回复
热议问题