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

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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

You Might Also Like