Skip to content

Instantly share code, notes, and snippets.

@docPhil99
Created October 20, 2021 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save docPhil99/4645866e368a37568c2842381630ea70 to your computer and use it in GitHub Desktop.
Save docPhil99/4645866e368a37568c2842381630ea70 to your computer and use it in GitHub Desktop.
Stop bash background commands on error

I have simple bash script that starts lots of processes. If one fails I want to stop everything. There maybe a better way to do this but I came up with this.

First create two scripts to test our main script. good_sleep that sleeps for 10 seconds and exits with no error.

#!/bin/bash
echo " good sleeping"
sleep 10
echo "done"

And bad_sleep that exits with an error after 2 seconds

#!/bin/bash
echo "bad sleeping"
sleep 2
echo "throw error"
exit 1

In bash I could have used wait to pause, but it waits until all the processes have finished. I want to stop things after the first process finishes. So I recored each PID in an array and poll this to see if they are still alive as follows.

#!/bin/bash
function error_finish {
echo "Error. Stopping all subprocesses"
kill 0
}
#trap exit and redirect to our command
trap error_finish EXIT 

# start each process and record its PID into an array
./good_sleep &
pid[0]=$!
./bad_sleep &
pid[1]=$!

num_pids=${#pid[@]}
echo "Running $num_pids processes"

while true ; do
	# loop over the pid array and test if the process is still 
	# alive. If not stop everything
	for i in "${pid[@]}"
	do
		if ! ps -p $i > /dev/null;
		then
			echo "Stopped"
			exit 1
		fi
	done
	sleep 1
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment