Syntax for a one-line infinite detached loop

一曲冷凌霜 提交于 2020-12-27 07:02:19

问题


I could run something in endless loop like this:

$ while true; do foo; done

I could run something detached like this:

$ foo &

But I can't run something detached in endless loop like this:

$ while true; do foo & ; done
-bash: syntax error near unexpected token `;'

How to run an infinite detached loop in one line of shell code?


回答1:


& is a terminator like ;, you can't mix them. Just use

while : ; do foo & done

I'd add a sleep somehwere, otherwise you'll quickly flood your system.




回答2:


If you want to run the loop in the background, rather than each individual foo command, you can put the whole thing in parentheses:

( while true; do foo; done ) &



回答3:


You should clarify whether you want

  • many copies of foo running in the background or
  • a single copy of foo running within a backgrounded while loop.

choroba's answer will do the former. To do the latter you can use subshell syntax:

(while true; do foo; done) & 



回答4:


All good answers here already - just be aware that your original loop with @choroba's correction will successfully make a very messy infinite string of processes spawned in quick succession.

Note that there are several useful variants. You could throw a delay inside the loop like this -

while true; do sleep 1 && date & done

But that won't cause any delay between processes spawned. Consider something more like this:

echo 0 > cond   # false
delay=10        # secs

then

until (( $(<cond) )) do; sleep $delay && foo & done

or

while sleep $delay; do (( $(<cond) )) || foo & done

then make sure foo sets cond to 1 when you want it to stop spawning.

But I'd try for a more controlled approach, like

until foo; do sleep $delay; done &

That runs foo in the foreground OF a loop running in background, so to speak, and only tries again until foo exits cleanly.

You get the idea.



来源:https://stackoverflow.com/questions/46527473/syntax-for-a-one-line-infinite-detached-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!