Logo

Linux Bash trap Command: 6 Practical Examples

Try this guide with our instant dedicated server for as low as 40 Euros

trap command

Having the ability to gracefully handle unexpected interruptions, clean up resources, or execute critical commands automatically when the script exits is a wonderful option for sysadmins.

The trap command delivers this capability.

The trap command in Bash is a powerful feature that intercepts and handles signals and other events while a script runs. It effectively handles unexpected interruptions and ensures cleanup operations are performed before the script exits.

In this tutorial, we will discuss the trap command and six practical examples of the command. We will start with an introduction to trap command and then move to the practical examples. 

Table Of Contents

  1. What is the trap Command?
    1. The Prerequisites for Using the trap Command
  2. 6 Practical Examples of trap Command
    1. Use Case #1: Clean Up Resources
    2. Use Case #2: Handle Interruptions
    3. Use Case #3: Reset a Trap
    4. Use Case #4: Handle Multiple Signals
    5. Use Case #5: Ignore Signals
    6. Use Case #6: Use Trap with a Specific Function
  3. Conclusion
  4. FAQs

What is the trap Command?

The trap command in Unix and Unix-like operating systems is used to define and handle signals and events in shell scripts. It allows users to specify actions to be taken when certain signals are received or when specific events occur.

It’s primarily used for cleaning up temporary files, handling interrupts, or performing specific actions before a script exits.

The Basic Syntax

The basic command syntax for the trap command is as follows:

# trap 'commands' signal1 signal2 …

Here, 

commands: This is the specific code executed when a trapped signal is received. It can be a simple command, a function defined elsewhere in your script, or even a series of commands separated by semicolons (;).

signals: Signals are predefined notifications sent to a process to indicate specific events. You can specify multiple signals by separating them with spaces.

Note: Each signal serves a specific purpose and can trigger different actions.

The following table summarizes common signals. 

common signals of trap command

Now that you have a basic understanding of the trap command, let us discuss 6 practical use cases that highlight the application of the command. However, before that, let us take a quick look at the prerequisites. 

The Prerequisites for Using the trap Command

Before diving in, ensure you have the following.

  • A user account with sudo or administrative privilege.
  • Text editor such as Vim or Nano

6 Practical Examples of trap Command

The trap command in Bash allows users to specify commands to execute when the script receives particular signals. Sysadmins and developers can use it for handling interrupts, triggering specific commands in response to the received signals, cleaning up temporary files, or performing other necessary actions when the script is terminated or interrupted. 

Use Case #1: Clean Up Resources

The following script highlight the use of the trap command to ensure temporary files or other resources are cleaned up even if the script exits abruptly.

#!/bin/bash 

# Create a temporary file

tempfile=$(mktemp)

# Define cleanup function

cleanup() {

echo "Cleaning up..."

rm -f "$tempfile"

}

# Set trap to call cleanup function on EXIT signal

trap cleanup EXIT

echo "Temporary file created: $tempfile"

# Simulate script operations

sleep 10

echo "Script completed."

Here, the cleanup function handles the deletion, and the trap command ensures it’s called when the script receives the EXIT signal.

Use Case #2: Handle InterruptionsConsider the following script that displays how the trap command handles interruptions. 

This script runs an infinite loop and sets a trap to handle the SIGINT signal (triggered by Ctrl+C). 

#!/bin/bash
# Set trap to handle SIGINT (Ctrl+C)
trap 'echo "Interrupt signal received!"; exit 1' SIGINT
echo "Running... Press Ctrl+C to trigger the trap."
while true; do
sleep 1
done

The trap triggers a function that prints a message and exits the script with a specific code (1 in this case).

Use Case #3: Reset a Trap

Consider the following script that shows how you can set and then reset a trap.

#!/bin/bash
# Set a trap for SIGINT
trap 'echo "SIGINT ignored"' SIGINT
echo "Trap set. Try Ctrl+C"
sleep 5
# Reset the trap for SIGINT
trap - SIGINT
echo "Trap reset. Try Ctrl+C again"
sleep 5

Here the SIGINT signal is trapped, and an informative message is displayed when Ctrl+C is pressed. 

Later, the trap for SIGINT is reset, allowing the default behavior (script termination) to resume.

Use Case #4: Handle Multiple Signals

You can handle multiple signals in a single trap command. Consider the following script that sets a trap for multiple signals (SIGINT, SIGTERM, SIGHUP). When any of these signals are received, the cleanup function is called, followed by script termination.

#!/bin/bash

# Define cleanup function

cleanup() {

echo "Cleaning up before exit..."

}

# Set trap to call cleanup function on SIGINT, SIGTERM, and SIGHUP

trap 'cleanup; exit' SIGINT SIGTERM SIGHUP

echo "Running script. Press Ctrl+C or send SIGTERM/SIGHUP to trigger the trap."

while true; do

sleep 1

done

Use Case #5: Ignore Signals

You may be surprised to learn that you can use the trap command to ignore signals received by the script. This script uses trap SIGINT to completely ignore the SIGINT signal, preventing the script from being interrupted by Ctrl+C.

#!/bin/bash

# Ignore SIGINT

trap '' SIGINT

echo "Try to interrupt me with Ctrl+C"

sleep 10

echo "You can't interrupt this script with Ctrl+C"

Use Case #6: Use Trap with a Specific Function

Consider the following script that sets up specific functions to handle different signals (SIGINT and SIGTERM): 

#!/bin/bash
# Define functions for specific signals

handle_sigint() {

echo "SIGINT received. Exiting gracefully..."

exit 1

}

handle_sigterm() {

echo "SIGTERM received. Shutting down..."

exit 0

}

# Set traps for specific signals

trap handle_sigint SIGINT

trap handle_sigterm SIGTERM

echo "Running script. Press Ctrl+C or send SIGTERM to trigger the traps."

while true; do

sleep 1

done

Here, each function performs specific actions and exits the script. 

Conclusion

Understanding and effectively using the trap command in Bash can greatly enhance the robustness and reliability of your scripts. By setting up traps, you can handle a comprehensive list of signals, ensuring that your scripts respond appropriately to interrupts, terminations, and system signals. 

Whether you need to clean up resources, handle unexpected interruptions, or ensure specific actions are performed before a script exits, the trap command is an invaluable tool for Bash scripting. 

FAQs

Q. What is a signal handler in Bash?

A signal handler in Bash is a function or command specified to execute in response to a specific signal. It uses the trap command to manage how the script reacts to various signals, such as interruptions or terminations.

Q. How do I use the trap command to perform cleanup tasks?

To perform cleanup tasks, you can define a function that contains the necessary cleanup commands and then use the trap command to call this function when specific signals are received.

Q. Why is the trap command a powerful tool in Bash scripting?

The trap command is powerful because it allows you to control the script’s behavior in response to signals, ensuring that important cleanup tasks are performed and that the script exits gracefully. It enhances the robustness and reliability of your scripts.

Q. Can I use multiple trap statements in a single script?

Yes, you can use multiple trap statements in a single script to handle different signals with different commands. Each trap statement can specify a different set of commands and signals.

Q. Where can I find the list of signals that can be used with the trap command?

The list of signals that can be used with the trap command can be found in the signal list of your operating system. Common signals include SIGINT, SIGTERM, SIGHUP, and SIGKILL. You can also refer to the man pages by running the man 7 signal in the terminal.

Q. What are standard signals in the context of the trap command?

Standard signals are predefined signals in Unix-like operating systems that can be intercepted using the trap command. Examples include SIGINT for interrupts, SIGTERM for termination requests, and SIGHUP for hangup signals.

Q. How do you write Bash code to handle signals using the trap command?

To handle signals using the trap command in Bash, you define the commands to execute when a signal is received and specify the signals to watch for.

Q. Can trap catch non-standard or custom signals in a Bash script?

Yes, the trap can catch custom signals such as SIGUSR1 and SIGUSR2. These user-defined signals can be used for custom purposes in your script.

Try this guide with our instant dedicated server for as low as 40 Euros