4 of 8
removed exec mid-script here, as it would exit the shell and make the trap meaningless (see discussion in comments on this answer)



_term() { 
  printf "%s\n" "Caught SIGTERM signal!" 
  kill -TERM $child 2>/dev/null

trap _term SIGTERM
echo "Doing some initial work....";
/bin/start/main/server --nodaemon &

wait $child

Normally, bash will not call trap handler when it's waiting child process. Using exec, your server will be start in a subshell, its pid is saved for later trap handler.

When SIGNTERM is caught, bash propagates it to child process, child process will be terminated, the wait call end. wait is used here to make sure that the script only quit after child process is terminated.

  • 137.3k
  • 35
  • 292
  • 373