[英]Syntax for a one-line infinite detached loop
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?如何在一行 shell 代码中运行无限分离循环?
&
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.我会在某个地方添加一个
sleep
,否则你会很快淹没你的系统。
如果您想在后台运行循环,而不是每个单独的foo
命令,您可以将整个内容放在括号中:
( while true; do foo; done ) &
You should clarify whether you want你应该澄清你是否想要
choroba 's answer will do the former. choroba的回答是前者。 To do the latter you can use subshell syntax:
要执行后者,您可以使用 subshell 语法:
(while true; do foo; done) &
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.这里已经有了所有好的答案 - 请注意,您使用 @choroba 更正的原始循环将成功地快速连续生成一个非常混乱的无限进程串。
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.然后确保
foo
在您希望它停止生成时将 cond 设置为 1。
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.它在后台运行的循环的前台运行
foo
,可以这么说,并且只会再次尝试直到foo
干净地退出。
You get the idea.你明白了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.