Syntax for a single-line Bash infinite while loop

2020-01-26 12:21发布

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 [ 1 ]
do
    foo
    sleep 2
done

12条回答
Emotional °昔
2楼-- · 2020-01-26 12:52

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;
查看更多
Rolldiameter
3楼-- · 2020-01-26 12:55

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
查看更多
狗以群分
4楼-- · 2020-01-26 13:02

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
查看更多
做自己的国王
5楼-- · 2020-01-26 13:06

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
查看更多
老娘就宠你
6楼-- · 2020-01-26 13: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
查看更多
爷的心禁止访问
7楼-- · 2020-01-26 13:09

A very simple infinite loop.. :)

while true ; do continue ; done

Fr your question it would be:

while true; do foo ; sleep 2 ; done
查看更多
登录 后发表回答