Signals in Bash are software interrupts sent to a program to indicate an event that occurred. They allow for process communication and control, often used for termination or suspension of processes.
There are two types of signals: synchronous (occur due to the execution of code by the process itself) and asynchronous (sent from outside the process). Examples include SIGINT (interrupt signal), SIGHUP (hang up signal), and SIGTERM (termination signal).
To handle signals in Bash, we use ‘trap’ command. It allows us to catch these signals and execute a piece of code when they occur. The syntax is ‘trap [COMMANDS] [SIGNALS]’. COMMANDS are scripts or commands executed when specified SIGNALS are received.
For example, to handle SIGINT, you’d write:
trap "echo 'SIGINT signal caught'" SIGINT
This script prints a message whenever it receives an interrupt signal.