Sample Header Ad - 728x90

Using set -e (errexit) with block of commands and executing another on fail of that block (SC2181)

2 votes
1 answer
339 views
I just found out about set -e as I was searching for an answer to "how to run many commands (without &&) and immediately stop on non-zero exit code of any of them?". The set -e was good enough for me until I discovered that
(set -e; false; echo here) || echo error
does produce here instead of error. But as I quickly found a solution of a new problem:
(set -e; false; echo here); [ $? -ne 0 ] && echo error
I also bumped to an old problem with $? instead of if cmd ([SC2181](https://www.shellcheck.net/wiki/SC2181)) . Now I have a new question: do I just ignore the SC2181 error, or is there a proper way to make it work? I also thought about trap but I don't know if set -e produces any signal at all. --- Note that
if ! (set -e; false; echo here); then
  echo error
fi
also prints here instead of error. From [ShellCheck](https://www.shellcheck.net/wiki/SC2181) website: > Apart from the redundancy, there are other reasons to avoid this pattern: > * [...] > * Scripts that run or are called with set -e aka errexit will exit immediately if the command fails, even though they're followed by a clause that handles failure. Which means that if statement is immune to errexit or disables it. Also note that absence of () or its substitution to {} will stop execution of next commands, including error checking command. --- P.S. I want to try to have as fewer ShellCheck errors in my scripts as possible (which are almost always indicate that the script is not optimized or have bugs). In addition, executing a lot of commands with appened && operator IMHO decreases code readability and editability, therefore I want to find a cleaner solution (at least for that specific block of commands in ()).
Asked by Andrew15_5 (271 rep)
Jan 27, 2023, 06:43 AM
Last activity: Jan 27, 2023, 05:11 PM