• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
NameHero® Blog

NameHero® Blog

Web Hosting Tips & Resources From NameHero

  • AI Agents
    • OpenClaw
    • Claude Code
    • n8n
    • Hermes Agent
    • Open WebUI
    • Docker
  • Hosting
    • Web Hosting
    • WordPress Hosting
    • WooCommerce Hosting
    • Enterprise Hosting
    • Email Hosting
    • HeroicGuard
    • GPU Hosting
    • Website Builder
  • VPS
    • Managed VPS
    • Unmanaged VPS
    • Flex VPS
  • Reseller
  • Gaming
  • Domains
  • Account
  • Blog Home
  • Categories
  • Authors

Demystifying The Bash Trap Command

CJ Saathoff

Published on: April 25, 2024

Categories: Linux Command Line 0

Before we dig into the trap command in bash, you will need to have some understanding of signals and shell scripting. The trap command is used to catch specified signals and perform an action in response.

In this blog post, we will demystify the trap command, and by the time you finish, you should be able to implement the trap command into your bash scripts.

Table of Contents
  • What Is Bash Trap?
  • When To Use A Trap?
  • Syntax
  • Signal List
    • Pseudo-Signals
  • Practical Examples
  • Conclusion

What Is Bash Trap?

Let’s draw a comparison to a physical trap, it’s set with the intention of catching something specific.

The bash trap command is a built-in function of the bash shell. This function is like a physical trap that can be set to catch something specific. In the case of the bash trap command, it is set to catch specific signals when running shell scripts. The signals could come from either the bash script or outside of it.

When To Use A Trap?

The trap command makes scripts more robust by executing a set of commands when the trap is triggered. Some use cases are cleanup functions, error handling, and graceful termination.

Syntax

The basic syntax for the trap command is below

trap [action] [signal]

The action is what you want to run when the trap is triggered.

The signal is the specific signal you want to trigger the trap.

Signal List

Because signal numbers can vary between Unix-like systems, make sure you are using the signal names.

To generate a list of supported signals run the following command

trap -l

Below are some of the more common signals used with the trap command.

  • SIGINT: This signal is generated when a user presses ctrl + c
  • SIGTERM: This signal is a request for the application to gracefully terminate
  • SIGQUIT: This signal is sent when a user presses ctrl +\
  • SIGHUP: This signal is typically generated when a terminal is closed
  • SIGUSR1 and SIGUSR2: These are user-defined signals
  • SIGALRM: This signal is generated from an alarm timer
  • SIGPIPE: This signal occurs when data is piped but no progress tries to read the piped data
  • SIGCHLD: This signal is sent to the parent when a child process terminates

To see a full list of most systems use the following command

man 7 signal

You will need to then scroll down to the Standard Signals section.

If you get a message about no manual entry you can use an online man page.

Pseudo-Signals

In addition, the standard signals trap has a few pseudo-signals. These signals can be used in place or alongside standard signals when using the trap command.

ERR when a command ends in a non-zero status triggers this trap. Be aware that commands in if statements, loops, or strung-together commands may not trigger this signal.

The EXIT trap is used to specify actions that should be done before the script exits.

DEBUG this signal triggers right before a command is to be run.

The RETURN signal is triggered after a function or sourced script exits.

Practical Examples

The below trap commands, are just a few examples of ways you can use the trap command in your shell scripts.

  1. The bellow command looks for the SIGINT signal (from a user pressing ctrl+c), and when the trap is triggered it prints out a message and then exits.
trap 'echo -e "\nThe script is terminated with Ctrl+C"; exit' SIGINT
  1. Next an example that uses a trap for a cleanup function
# Function for cleanup on script exit
cleanup_on_exit() {
    echo "Performing cleanup tasks before script exit..."
    # Add cleanup tasks here
}

# Trap for cleanup on script exit
trap 'cleanup_on_exit' EXIT

# Main script here
  1. This last one uses a custom signal to trigger a configuration reload.
# Function to reload configuration
reload_config() {
    echo "Reloading configuration..."
    # Add code to reload configuration here
}

# Trap signals for configuration reload
trap 'reload_config' SIGUSR1

# Main script logic
echo "Script started. Will reload when sent SIGUSR1 or SIGUSR2 to reload."
while true; do
    # Add main script logic here
    sleep 1
done

Conclusion

If you’re shell scripting and want to make your scripts more robust, the trap command may be able to help. In this post, we begin by clarifying what the trap command is and when you might want to use it. Next went over syntax, signals, and pseudo-signals the parts that make up the completed command. And to wrap up some practical examples, that might inspire ideas on how you can use the trap command.

CJ Saathoff

Embracing a lifelong passion for technology since childhood, CJ delved into the intricate workings of systems, captivated by the desire to understand the unknown. This innate curiosity led to his discovery of Linux, a revelation that resonated deeply. With more than 7 years of on the job experience, he’s honed his technical skills as a Geek and Senior Linux Systems Administrator.

Related Posts

Resolving the “Fatal: Refusing to Merge Unrelated Histories” Error

The "fatal: refusing to merge unrelated histories" occurs when you try and merge an unrelated repo into your own. Here's what it means.

Bash Conditional Expressions: [[ vs [ vs test

In bash scripts, we use conditional statements frequently. Whether it’s in an “if fi” logic block or within a “while” or “do” loop, we evaluate statements all the time to determine whether they’re true or false, and perform various actions based on the result. True to form, there are multiple ways to do this, and […]

Symbolic Links vs Hard Links in Linux

Linux offers various methods for referencing files and directories through other files and directories, without creating copies of the original. If you have color coding enabled in your bash terminal, you might have seen some folders full of files of a different color from regular files. There’s a good chance that these are all symbolic […]

Curl Headers, Cookies, and Authentication

You can do a lot more with curl, than just sending requests. Here's how to change the headers, the cookies, and how to authenticate users.

Reader Interactions

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Follow & Subscribe

Exclusive promos, content and more!


Most Popular Posts

NameHero’s Recommended WordPress Plugin and Theme Setup

WordPress Hosting vs. Web Hosting – What’s The Difference?

How To Increase The InnoDB Buffer Pool Size

How To Fix A Stuck All-in-One WP Migration Import

How To Add A Subdomain In Cloudflare

Top Categories

  • WordPress
  • WordPress Tutorials
  • OpenClaw Hosting
  • Enterprise Hosting
  • WooCommerce
  • Web Hosting
  • Resellers
  • Website Security
  • Website Development
  • Website Performance
  • VPS Hosting
  • SEO Tips
  • Announcements
  • Domain Registration
NameHero

NameHero® proudly provides web hosting to over 40,000 customers with 99.9% uptime to over 750,000 websites.

  • Master Card
  • Visa
  • American Express
  • Discover
  • Paypal
Products
  • Web Hosting
  • Managed VPS Hosting
  • Unmanaged VPS Hosting
  • Flex VPS Hosting
  • WordPress Hosting
  • WooCommerce Hosting
  • Reseller Hosting
  • Enterprise Hosting
  • GPU Hosting
  • Email Hosting
  • HeroicGuard
  • Domains
  • Website Builder
  • AI Agent Hosting
Help & Support
  • NameHero Blog
  • NameHero Gaming Blog
  • Support
  • Help Center
  • Migrations
  • Affiliates
  • Gaming Affiliates
  • Call 1-855-984-6263
Company
  • About Us
  • Contact Sales
  • Reviews
  • Uptime
  • We're Hiring

Copyright © 2026 Name Hero, LLC. All rights reserved.
NameHero® is a registered trademark.

  • Privacy Policy
  • Terms of Use
  • Acceptable Use Policy
  • Payment Policy
  • DMCA