Another useful capability I use to do cleanup is `trap`.
function cleanup {
...
}
trap cleanup EXIT
See more here: http://linux.die.net/Bash-Beginners-Guide/sect_12_02.html