#trap ... EXIT runs when the shell ends, whatever way it ends;
#a function with ( ) instead of { } runs in a subshell
#with its own trap, like try ... finally
throwIfTrue() (
trap 'echo "finally"' EXIT
if [[ $1 == true ]]; then
echo "except"
exit 1
fi
)
throwIfTrue true
#printed: "except" and "finally"
throwIfTrue false
#printed only "finally"
#the usual job of the trap is cleaning up: the file goes away
#even when the subshell ends with an error
(
trap 'rm -f temp.txt' EXIT
echo "data" > temp.txt
exit 1
)
[[ -e temp.txt ]] && fileLeft=true || fileLeft=false
#fileLeft is false
echo "fileLeft is $fileLeft"