Bash’s errexit and subshells

Python’s try-except-finally construct is pretty nice and I was looking for something similar in bash. I imagined something like:

( # Try
  set -e
  run_a_cmd
) || { # Except
  echo "ERROR"
}
# Finally
cleanup

The assumption is that the “Try”-block will fail if any command inside the block fails, becauseset -e is used to set errexit. But this does not work. Why it is not working was not directly obvious to me. The reason is now - and you can look this up in the bash manpage - that set -e or errexit is ignored if a subshell ((…)) is used with || or && - and this is the case above.

The following construct is working:

( # Try
  set -e
  run_a_cmd
)
test $? -gt 0 && { # Except
  echo "ERROR"
}
# Finally
cleanup

This does work because || got eliminated.

This construct is a bit less nice, but still helpful.

::: {#footer} [ January 6th, 2016 10:58am ]{#timestamp} [fedora]{.tag} [bash]{.tag} [magic]{.tag} [awkward]{.tag} :::