Skip to content

Instantly share code, notes, and snippets.

@mariocesar
Created April 8, 2018 21:48
Show Gist options
  • Select an option

  • Save mariocesar/89e47a033c23cda43748664423a183b9 to your computer and use it in GitHub Desktop.

Select an option

Save mariocesar/89e47a033c23cda43748664423a183b9 to your computer and use it in GitHub Desktop.
Bash script that runs forever and wait for signals.
#!/usr/bin/env bash
catch_kill() {
echo "Caught SIGKILL signal!"
kill -KILL "$pid" 2>/dev/null
}
catch_term() {
echo "Caught SIGTERM signal!"
kill -TERM "$pid" 2>/dev/null
}
catch_quit() {
echo "Caught SIGTERM signal!"
kill -QUIT "$pid" 2>/dev/null
}
catch_ctrlc() {
echo "Caught ctrl+c!"
kill -KILL "$pid" 2>/dev/null
}
trap catch_term SIGTERM
trap catch_kill SIGKILL
trap catch_quit SIGQUIT
trap catch_ctrlc INT
echo "Script is running! waiting for signals."
pid=$$
sleep infinity
@AndresPinerosZen
Copy link

sleep is actually running in the foreground and won't allow the signals to be trapped. You need to run the process in the background and wait.

sleep infinity &
wait

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment