Exit handler in bash with trap
Metin Yazici
•
2021-02-24 - 1 year ago
•
1 min read
With trap
, we can safely declare clean-up statements. It is executed on exit
from a function, that the exit can either be natural or as the result of an
error. The basic syntax is:
trap [action] [condition]
For example, we want to test things on a local database but we want to remove the database if a command exits with a non-zero status (or if an error occurs).
start_test_db.sh
#!/usr/bin/env bash
test_local_db() {
echo "++ starting test container"
docker run --name my-test-db -e POSTGRES_PASSWORD=password -d postgres
on_exit() {
echo "++ stopping and removing test container"
docker container stop my-test-db
}
trap on_exit EXIT
# let's say we have an error here:
echo "++ an error happened!" && exit 1
}
test_local_db
++ starting test container
653c90d1
++ an error happened!
++ stopping and removing test container
my-test-db
More documentation can be seen at man trap
.
Questions or comments? Join via Reddit.