Home » Bash » Shell Script Wrapper — Make a script auto-respawn on exit

This shell script wrapper provides a way for you to run a script and ensure that if it crashes or is killed that it immediately restarts.

#!/bin/sh -eu
if test $# -eq 0; then
  echo Please give a command to start >&2
  exit 75
fi
# execute the monitored command
${1+"$@"} &
# get the PID of monitored command
pid=$!
# make sure when this script finishes, it will kill the started command
trap 'kill -9 $pid' EXIT
# wait for the monitored command to finish
wait $pid
trap '' EXIT
# recursively restart everything again
exec $0 ${1+"$@"}