How to do it...

Let's start our activity as follows:

  1. Open a terminal and begin a new script called mytrap.sh with the following contents:
#!/bin/bashfunction setup() {  trap "cleanup" SIGINT SIGTERM  echo "PID of script is $$"}function cleanup() {  echo "cleaning up"  exit 1}setup# Loop forever with a noop (:)while :do  sleep 1done
  1. Execute the script with $ bash mtrap.sh.
  2. Press Enter several times and watch the behavior of the program.
  3. Press Ctrl + C; notice anything different?

Get Bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.