..

trap cleanup EXIT

With trap cleanup EXIT you can ensure that any necessary cleanup is performed in your bash scripts whenever the script exits. cleanup in this case is the function to be executed.

function cleanup {
  # Cleanup code
}

trap cleanup EXIT

# Rest of your code

Even if the script exits with a non-zero exit code or is interrupted, from my minimal testing it does still trigger. However, this behaviour doesn’t seem to be completely standardized in POSIX.

Fun fact: EXIT is a pseudo-signal, meaning it is a bash builtin and not an official OS signal. trap -l will not list it.