In my Bash scripts, I would like to make sure that the script exits as soon as there is an error. (E.g., to avoid a mistaken rm -f *
after a failed cd some_directory
.) For this reason, I always use the -e
flag for bash.
Now, I would also like to execute some cleanup code in some of my scripts. From this blog post I gathered
#!/bin/bash
cd invalid_directory
echo ':('
function clean_up {
echo "> clean_up"
exit 0
}
trap clean_up EXIT
The output I get is
./test.sh: line 3: cd: invalid_directory: No such file or directory
:(
> clean_up
so it does what's advertised. However, when using -e
for bash, I'm only getting
./test.sh: line 3: cd: invalid_directory: No such file or directory
so the script exits without calling clean_up
.
How can I have a bash script exit at all errors and call a clean up script every time?