Getting Ensure/Finally Functionality in Shell Command

bashcommand lineexitexit-status

I need to know whether a command has succeeded or failed, and unconditionally run some cleanup afterward.

Neither of the normal options for executing sequential commands seem to be applicable here:

$ mycmd.sh && rm -rf temp_files/    # correct exit status, cleanup fails if mycmd fails
$ mycmd.sh ;  rm -rf temp_files/  # incorrect exit status, always cleans up
$ mycmd.sh || rm -rf temp_files/    # correct exit status, cleanup fails if mycmd succeeds

If I was going to do it in a shell script, I'd do something like this:

#!/usr/bin/env bash
mycmd.sh
RET=$?
rm -rf temp_files
exit $RET

Is there a more idiomatic way to accomplish that on the command line than semicolon-chaining all those commands together?

Best Answer

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 )
Related Question