Bash – How to Run an Infinite Loop in the Background

bash

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

Best Answer

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
Related Question