Cleanly create tempfiles using mktemp and remove them using traps instead of removing them in the end of the script. This way, you make sure the tempfiles are removed properly even if the script is killed or interrupted.