Getting "ensure" / "finally" functionality in a shell command (not script)?
Newlines in a script are almost always equivalent to semicolons:
mycmd.sh; ret=$?; rm -rf temp_files; exit $ret
In response to the edit:
Alternatively, you could also use a trap
and a subshell:
( trap 'rm -rf temp_files' EXIT; mycmd.sh )
If you're looking for a copy of some languages' try { } finally { }
,
there is another way: using the trap
builtin in bash
and other POSIXy shells (see help trap
).
#!/bin/bash
# exit with this by default, if it is not set later
exit_code=0
# the cleanup function will be the exit point
cleanup () {
# ignore stderr from rm incase the hook is called twice
rm -rf "temp_files/" &> /dev/null
# exit(code)
exit $exit_code
}
# register the cleanup function for all these signal types (see link below)
trap cleanup EXIT ERR INT TERM
# run your other script
mycmd.sh
# set the exit_code with the real result, used when cleanup is called
exit_code=$?
Read about the trap command's arguments.
Note that cleanup
is called:
- if this script is sent SIGINT or SIGTERM or if CTRL-C is pressed (SIGINT)
- if this script exits normally with 0
- if mycmd.sh exits with nonzero status (maybe not what you want -- remove
ERR
from trap's arguments to disable)
In zsh
:
{mycmd.sh} always {rm -rf temp_files}
The always part will be executed even in case of an error like a glob with no match or runtime syntax error that would exit the script.