trap

2024-07-29

Understanding Signals

Before diving into trap, it’s important to grasp the concept of signals. Signals are software interrupts sent to a process to notify it of an event, such as a termination request (SIGTERM), an interrupt from the keyboard (SIGINT), or a hangup (SIGHUP). These signals, represented by numbers or names (e.g., SIGINT, SIGTERM), trigger predefined actions within the process, unless otherwise handled.

The trap Command: Structure and Usage

The basic syntax of the trap command is:

trap 'command' signal

Here:

Practical Examples

Let’s illustrate the usage of trap with many examples:

1. Handling Ctrl+C (SIGINT):

This script prevents Ctrl+C from interrupting a long-running process, instead printing a message and exiting gracefully:

#!/bin/bash

trap 'echo "Caught Ctrl+C. Exiting gracefully..."' INT


sleep 10

echo "Process completed successfully."

2. Cleaning up Temporary Files:

This script uses trap to delete temporary files upon termination (either normal exit or via signal):

#!/bin/bash

temp_file=$(mktemp)
echo "Temporary file created: $temp_file"

trap 'rm -f "$temp_file"; echo "Temporary file deleted."' EXIT


sleep 5

echo "Work completed."

Note the use of EXIT. EXIT is a special signal that’s sent when the script exits normally.

3. Handling Multiple Signals:

You can handle multiple signals within a single trap command, separating signal names with spaces:

#!/bin/bash

trap 'echo "Signal received! Cleaning up..."' INT TERM

4. Ignoring Signals:

To ignore a specific signal, use an empty string as the command:

#!/bin/bash

trap "" HUP

5. Restoring Default Signal Handling:

To restore the default action for a signal, use the trap command with only the signal name:

#!/bin/bash

trap INT  # Restores the default action for SIGINT (typically termination)

6. Using Variables within the trap command:

It’s possible to use variables defined in your script inside the trap command:

#!/bin/bash
my_variable="Hello from the script"
trap 'echo "Variable value: $my_variable"' EXIT
sleep 2

These examples demonstrate the versatility of trap in managing signals and improving the robustness of your shell scripts. Proper use of trap can prevent data loss, ensure graceful termination, and improve overall script reliability. Remember to choose the appropriate signal(s) based on the specific scenario and desired behavior.