« Back to Index

[Trap exit and error (defer cleanup execution when bash script fails)]

View original Gist on GitHub

Tags: #bash #trap #catch #errorhandling

1.help.md

help trap

Seems you can also use trap <fn> RETURN so the defined function will be called every time the script that’s being run has finished executing.

trap error.bash

#! /bin/bash

err_report() {
    echo "Error on line $1"
}

# if you wrap the function to be called in a single quote string,
# then anything following it will be passed to the function!
#
# so in the following example we pass the shell's LINENO variable
# which indicates what the error line was.
#
# we then access that via $1 within the err_report function, but
# we could also have just used $* to reference all arguments passed
# in case we passed multiple arguments.
trap 'err_report $LINENO' ERR

echo hello | grep foo  # This is line number 9

# $ ./foo.sh
# Error on line 9

trap exit.bash

#!/bin/bash

set -e

function cleanup {
  echo "Removing /tmp/foo"
  rm  -r /tmp/foo
}

trap cleanup EXIT
# trap cleanup ERR <- so only cleans on errors
mkdir /tmp/foo
asdffdsa # fails

trap multiple.bash

#!/bin/bash

function cleanup {
  echo "running cleanup $*"
}

trap cleanup EXIT
trap 'cleanup uh-oh it went wrong' ERR

asdasdasd # would cause ERR to fire and thus cleanup function would get extra arguments

# otherwise the script would just exit naturally and so the EXIT signal would be handled.