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.

List of trap signals

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.

Signals available

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 DEBUG, EXIT and ERR.

List of trap signals

Versions

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

Examples

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.

  1. return_codes => Has the return code of the last command, including the pipes. For example, if you run ls -l | grep -i aaa and there is no aaa file, the last command with the error was the grep with return code 1
  2. array_length => This is to check the length of the array return_codes
  3. return_code => It’s the last return code of the return_codes

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.

  1. Run the script ./trap.sh
  2. Get the curl: (6) error
  3. Print the FATAL message
  4. Get the ok from Slack
  5. And finally confirming the exit code of the script

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Matheus Lozano

A SysAdmin who love to automate everything — DevSecOps, SRE and Chaos Engineer, let's share our skills.