17

How can I run an infinite loop in the background, while continuing on with the script's execution?

Example "script":

while true; do something_in_the_background; done

do_something_while_the_loop_goes_on_in_the_background

for 1 2 3; do somethingelse; done

exit 0

This (notice the &) seems to crash the whole system after a short while:

while true; do
  something_in_the_background &
done

do_something_while_the_loop_goes_on_in_the_background

for 1 2 3; do somethingelse; done

exit 0
  • Not suprised you are creating lots of processes. – Ed Heal Aug 17 '15 at 19:01
  • Asking directions for a fork bomb? – Baazigar Aug 17 '15 at 19:29
  • 1
    Could you please tell the intention behind running an infinite loop in the background ? – neuron Aug 17 '15 at 19:38
30

With the & inside the loop it will start a new process in the background and as fast as it can do it again without waiting for the first process to end. Instead I think you want to put the loop into the background, so put the & on the loop itself like

while /bin/true; do
    something_in_the_background
done &

# more stuff
10
while : ; do something ; done &
  • Earlier Bourne shells didn't have true and false as built-in commands. true was instead simply aliased to :, and false to something like let 0.

  • & at the end of the line backgrounds the process

  • : is the null command, as described by "help :": No effect; the command does nothing. Exit Status: Always succeeds.
  • 2
    Your answer would be greatly improved by explaining it—the OP may not know what : means and probably doesn't know why you've moved the & to the end. Also, changing the spacing to make it a one-liner is just confusing—it's a change which is very visible but is entirely unimportant. – derobert Aug 17 '15 at 19:41
  • Edited the post as per your reviews – John Aug 17 '15 at 19:44
0

Putting sleep of say .1 or .01 seconds would make your loop more CPU friendly. But as pointed out be Eric Renouf, the & should be at the end of the loop, not inside it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.