问题
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