0

I am sure this has been covered but not sure how to find the answer:

#!/usr/bin/env bash

set -e;
false &
wait;
echo "lol"

if we run this, we get "lol".

Is there a way to exit the script if the background command (in this case "false") exits with non-zero?

In this case, set -e; does not seem to prevent the script from continuing if a command exits with non-zero, if that command is run in the background.

  • I guess trap is one way to do this, but it would be nice to do this without using trap if possible. – Alexander Mills Mar 24 '18 at 4:33
1

If you're using a recent version of bash (I think this was introduced in bash 4), then you can use wait -n.

Otherwise, you can pass wait an argument with the pid of the background process you started, which is returned in $! right after you do.

See the documentation of the wait command for more details on return status of the wait command.

This should do it:

set -e
false &
wait -n
echo "lol"

And this is fine too:

set -e
false &
background_pid=$!
wait "${background_pid}"
echo "lol"
  • wait %1 would also work in those examples, including with other shell implementations (eg: dash or busybox sh) – A.B Mar 24 '18 at 15:31

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.