Dcycle Blog

Cleaning up after a failed bash script

February 12, 2016

If your bash script is called test.sh, and you need to clean up temporary files regardless of the exit code, you could do something like this:

# test.sh
# pass all arguments to the main script
./test-main.sh "$@"
echo 'cleanup'
if [[ $EXITCODE -eq 1 ]]; then
  echo 'about to exit with 1'
  exit 1;
  echo 'about to exit with 0'
  exit 0;

And then put your logic in test-main.sh, like this:

# test-main.sh
# set -e propagates errors and terminates the script
set -e
# do your stuff