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.
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.
- 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
- 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
- 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.
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.
Leave a Reply