Bash scripts can trap EXIT signal and run clean up commands before exit. This is useful if a user kills a script or the script gets killed on its own due to errors. Here is sample code to which traps EXIT signal and calls a custom function onexit.

#!/bin/bash
## Use set -e to exit on error
set -e
function onexit() {
echo "In onexit function"
}
trap onexit EXIT
echo "Before calling non_existing_command"
non_existing_command
echo "After calling non_existing_command"Before calling non_existing_command In onexit function
Env: GNU bash, version 4.2.46