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条回答
我欲成王,谁敢阻挡
2楼-- · 2020-01-26 12:43

For simple process watching use watch instead

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-01-26 12:45
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
查看更多
Deceive 欺骗
4楼-- · 2020-01-26 12:46

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;
查看更多
神经病院院长
5楼-- · 2020-01-26 12:50

Colon is always "true":

while :; do foo; sleep 2; done
查看更多
Emotional °昔
6楼-- · 2020-01-26 12:50

You can use semicolons to separate statements:

$ while [ 1 ]; do foo; sleep 2; done
查看更多
何必那么认真
7楼-- · 2020-01-26 12:51

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.

查看更多
登录 后发表回答