Bash has a way of intercepting signals to perform actions. This is a nice way to have cleanup functions that can be executed before the program exists. Here are some examples in how you can setup a function that is capable of intercepting signals.
#!/bin/bash
# settting up the trap …