strboul blog

Exit handler in bash with trap


With trap, we can safely declare clean-up statements. It is executed on exit from a function, that the exit can either be controlled or as the result of an error.

The basic syntax is:

trap [action] [condition]

The example below is to start a local postgres database and remove it on error in the same script, e.g. when a command exits with a non-zero status.

start_test_db.sh

#!/bin/bash

set -e

on_exit() {
  echo "++ stopping and removing test container"
  docker container stop my-test-db
}

test_local_db() {
  echo "++ starting test container"
  trap on_exit EXIT
  docker run --name my-test-db -e POSTGRES_PASSWORD=password -d postgres

  # let's say we have an error here:
  echo "++ an error happened!" && exit 1

  echo 'it continues...'
}

test_local_db
# ++ starting test container
# 509d1be6c59bf92cd3dbadbb6971ebcfa9cccbe70f669625a584d4619c12c846
# ++ an error happened!
# ++ stopping and removing test container
# my-test-db

More documentation can be seen at man trap.