Bash trap Command Explained


Bash is a powerful shell used in Linux systems for executing commands and managing processes. trap command in Bash is a useful tool for handling signals and errors that can occur during script execution. In this article, we'll explain what Bash trap command is, how it works, and give some examples of how you can use it.

What is Bash Trap Command?

The Bash trap command is a mechanism that allows you to handle signals and errors that can occur during script execution. Signals are software interrupts that are sent to a process to notify it of an event, such as a user interrupt or a system error. trap command allows you to specify how your script should respond to these signals.

In Bash, you can specify a trap command for a particular signal by using trap command followed by action you want to take. For example, if you want your script to perform a particular action when it receives SIGINT signal (generated by pressing Ctrl-C), you can use following command −

trap 'echo "Signal SIGINT caught"' SIGINT

This command specifies that when script receives SIGINT signal, it should execute echo command, which will print message "Signal SIGINT caught" to console.

How does Bash Trap Command work?

When you execute a Bash script, operating system sends signals to your script to notify it of various events. These signals can be used to terminate your script, pause it, or handle other events. trap command allows you to specify how your script should respond to these signals.

When you specify a trap command for a signal, Bash will execute that command when script receives corresponding signal. command can be any valid Bash command or a sequence of commands separated by semicolons. When trap command is executed, any variables or functions that were defined in current shell environment will be available.

Bash Trap Command Examples

Here are some examples of how you can use Bash trap command to handle signals and errors in your scripts −

Example 1: Handling SIGINT Signal

The SIGINT signal is generated when user presses Ctrl-C. By default, when a Bash script receives this signal, it will terminate. You can use trap command to handle SIGINT signal and prevent script from terminating. For example, following script will print a message to console when it receives SIGINT signal −

#!/bin/bash

trap 'echo "Signal SIGINT caught"' SIGINT

while true
do
   echo "Press Ctrl-C to generate SIGINT signal"
   sleep 1
done

When you execute this script, it will enter an infinite loop and print a message to console every second. If you press Ctrl-C, script will generate SIGINT signal, and trap command will execute, printing message "Signal SIGINT caught" to console.

Example 2: Handling ERR Signal

The ERR signal is generated when a command in your script exits with a non-zero status. By default, when a Bash script encounters an error, it will terminate. You can use trap command to handle ERR signal and prevent script from terminating. For example, following script will print a message to console when a command exits with a non-zero status −

#!/bin/bash

trap 'echo "Command exited with non-zero status"' ERR

echo "This command will exit with a non-zero status"
false

echo "This command will not execute"

When you execute this script, it will print message "This command will exit with a non-zero status" to console and then execute false command, which will exit with a non-zero status. trap command will then execute, printing message "Command exited with non-zero status" to console. script will not terminate, and last echo command will not execute.

Example 3: Cleaning Up Resources on Exit

You can use trap command to perform cleanup tasks when your script exits, regardless of exit status. For example, if your script creates temporary files or locks resources, you can use trap command to ensure that these resources are released when script exits. following script demonstrates how to use trap command to remove a temporary file when script exits −

#!/bin/bash

# Create a temporary file
temp_file=$(mktemp)

# Define a function to remove temporary file
cleanup() {
   rm -f $temp_file
   echo "Temporary file $temp_file removed"
}

# Register cleanup function to execute on exit
trap cleanup EXIT

# Do some work with temporary file
echo "Writing to temporary file $temp_file"
echo "Hello, world!" > $temp_file

# script will exit, and cleanup function will execute, removing temporary file

When you execute this script, it will create a temporary file using mktemp command and write some text to it. trap command is used to register cleanup function to execute when script exits. cleanup function removes temporary file and prints a message to console. When script exits, either by completing its work or by encountering an error, cleanup function will execute, removing temporary file.

Advanced use cases for Bash trap command

Debugging

You can use trap command to debug your scripts by adding debug commands to trap commands. For example, you can use following command to print current line number when script receives ERR signal −

trap 'echo "Error on line $LINENO"' ERR

This command uses built-in Bash variable $LINENO to print current line number when ERR signal is received.

Conditional Traps

You can use conditional statements in your trap commands to execute different commands depending on context in which signal is received. For example, you can use following command to execute a different command depending on whether script is running in foreground or background −

trap '[ "$$" != "$BASHPID" ] && echo "Script running in background" || echo "Script running in foreground"' SIGINT

This command uses built-in Bash variable $$ to compare process ID of script with process ID of current Bash shell (BASHPID). If script is running in background, first command will execute. Otherwise, second command will execute.

Logging

You can use trap command to log events in your scripts by redirecting output to a log file. For example, you can use following command to log current date and time when script exits −

trap 'echo "$(date): Script exited"' EXIT >> /var/log/myscript.log

This command uses date command to print current date and time and redirects output to /var/log/myscript.log file.

Graceful Termination

You can use trap command to ensure that your scripts terminate gracefully by releasing any resources they have acquired. For example, you can use following command to remove a lock file when script exits −

lockfile=/var/run/myscript.lock

# Create lock file
touch $lockfile

# Define cleanup function to remove lock file
cleanup() {
   rm -f $lockfile
}

# Register cleanup function to execute on exit
trap cleanup EXIT

# Do some work

# script will exit, and cleanup function will execute, removing lock file

This command creates a lock file using touch command and registers a cleanup function to remove lock file when script exits.

Conclusion

The Bash trap command is a powerful tool for handling signals and errors in your scripts. You can use it to customize behavior of your scripts in response to various events, such as user interrupts or errors. By using trap command, you can ensure that your scripts gracefully handle unexpected events and release any resources they may have acquired. Hopefully, this article has given you a good introduction to Bash trap command and some ideas for how you can use it in your own scripts.

Updated on: 13-Apr-2023

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements