Is It Possible to Execute a While Loop in the Background?

Is It Possible to Execute a While Loop in the Background?

I am creating a shell script and want to execute a certain while loop in the background. Normally, I would create a new watch.sh file containing:

while true; do ...; done

Then, in my main shell script, I would do:

nohup watch.sh >/dev/null 2>&1 &

My question is if this could be done without introducing a watch.sh file? That is, is it possible to directly run a certain while loop in the background? Would something like the following work?

while true; do ...; done &

This is a shell script, but I can move on to bash if needed.

1 Answer

Yes, sh-like shells (including bash/zsh) let you use any block (compound command) the same way as a regular command, automatically starting a subshell process if necessary – it can be used as part of a pipeline, put into background, redirected, and even has its own 'exit code' and can be used in conditions.

3

Your Answer

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

David Miller
Author

David Miller

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.