• Matheus Lozano

How to trigger an action at the end of the Shell/Bash script

Updated: Jan 29

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 signals that can be used on Bash / Shell trap
List of trap signals

Replica: https://lozanomatheus.medium.com/52b0ba9c157e?source=friends_link&sk=6ef26ede09c14fc41bd008ef78d1e42b

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.


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.

  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

Read more

Trap man page - Trap signals and other events

The Bash Trap Command

Bash trap command

Bash declare builtin command