trapping errors and making sure the function runs at anycost in bash

Recently, I came up with a problem where I have to run the function at any cost. A good example will be to send notification of jenkins build every time even though it fails. There is no problem if my bash script runs without failure but what if the script fails and if there are exit 1 added  to the bash script. To overcome this I came through trap concept in bash which will catch the error and than we can do some action based on it.

A simple example would be

trap "echo some error occured" 0
echo "this will run no problem"
exit 0

Here, the echo command will run because it detected the 0. if that case does not come the command in the trap will not execute.

Another trap example with function:

#!/bin/bash
trap "two" EXIT INT TERM
function one(){
 echo "this function run first and exits we want to confirm function2 must run"
exit 1
}

function two(){
  echo "this has to run at anycost"
}

#function call
one
two

Here, the function two will execute even though the function is meant tot be stopped at one as we have exit 1 in there.

This was the easiest example of trap I could come up with.

Leave a Reply