How it works...

Let's understand our script in detail:

  1. The mytrap.sh script leverages functions and the trap call. Inside of the setup function, we set the function to be called by the trap command. Therefore, when Ctrl + C is called, the cleanup function is executed.
  2. Running the script will cause the script to run forever after printing out the PID of the script.
  3. Pressing regular keys such as Enter will not have an effect on the program.
  4. Pressing Ctrl+ C will echo cleanup on the console and the script will exit using the exit command.

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.