How to trigger an action at the end of the Shell/Bash script
Using Bash/Shell trap, a built-in command to define any action to be executed before exiting the Bash or Shell script. You can define multiple actions and per signal.
trap — ‘’ SIGTSTP
trap — ‘’ SIGTTIN
trap — ‘’ SIGTTOU
How it works
The Bash/Shell trap is a built-in command that can be used to trigger an action at the end of the script according to the signal. For example, you can use the
ERR to run a function in case something goes wrong. Use the
EXIT signal to run something every time that exists the script.
Note: Defining another action within the same signal will override the trap.
The Shell Trap built-in command and it’s available on most of the Linux and Unix distributions.
Currently, there are 65 signals (62 listed + 3) and not all of them are supported. You can list the signals available by running
trap -l . The other three are
These are the versions that I’m using.
CentOS Linux release 7.9.2009
Linux 4a48b06b2344 4.19.121-linuxkit
Bash => 4.2.46(2)-release
cURL => 7.29.0
A code example
This example I will show what happens if the
curl has an invalid URL.
Note: The first function
log is for logging purpose only and I’ll be covering this in a future post. For now, let’s focus on the function
fatal_log and the
trap fatal_log ERR.
Exampling the code
At the beginning of the
fatal_log function, I defined three local variables. The intention was to preserve the return code from the failed command and use it to exit from the script.
- return_codes => Has the return code of the last command, including the pipes. For example, if you run
ls -l | grep -i aaaand there is no
aaafile, the last command with the error was the
grepwith return code
- array_length => This is to check the length of the array
- return_code => It’s the last return code of the
After defining the local variables, I create a function
log to print a
FATAL error in the terminal and send a notification via Slack.
A live example
In the video below, you can confirm the order mentioned above.
- Run the script
- Get the
- Print the
- Get the
- And finally confirming the exit code of the script
The Bash Trap Command
If you've written any amount of bash code, you've likely come across the trap command. Trap allows you to catch signals…
Bash trap command
The most common signal of bash is SIGINT (Signal Interrupt). When the user presses CTRL+C to interrupt any process from…