Replace "&& exit 1" by "! command || exit 1"

Benjamin Drung
2025-01-13 14:18:47 +01:00
parent 7cdb5fd5e2
commit 17bbd4670e

@@ -1,4 +1,4 @@
## This `!` is not on a condition and skips errexit. Use `&& exit 1` instead, or make sure `$?` is checked. ## This `!` is not on a condition and skips errexit. Add `|| exit 1` or make sure `$?` is checked.
### Problematic code: ### Problematic code:
@@ -12,7 +12,7 @@ rest
```sh ```sh
set -e set -e
false && exit 1 ! false || exit 1
``` ```
### Rationale: ### Rationale:
@@ -21,7 +21,7 @@ ShellCheck has found a command inverted with `!` that may have no effect. In par
The most common reason for this is thinking that it'll trigger `set -e` aka `errexit` if a command succeeds, as in the example. This is not the case: `!` will inhibit errexit both on success and failure of the inverted command. The most common reason for this is thinking that it'll trigger `set -e` aka `errexit` if a command succeeds, as in the example. This is not the case: `!` will inhibit errexit both on success and failure of the inverted command.
Using `&& exit ` will instead exit when failure when the command succeeds. Adding `|| exit ` will instead exit with failure when the command succeeds.
### Exceptions: ### Exceptions:
@@ -39,3 +39,4 @@ In this case, you can [[ignore]] the warning.
### Related resources: ### Related resources:
* StackOverflow: [Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/questions/39581150/why-do-i-need-parenthesis-in-bash-set-e-and-negated-return-code/39582012) * StackOverflow: [Why do I need parenthesis In bash `set -e` and negated return code](https://stackoverflow.com/questions/39581150/why-do-i-need-parenthesis-in-bash-set-e-and-negated-return-code/39582012)
* [The "Use && exit 1" for SC2251 can result in a wrong exit code](https://github.com/koalaman/shellcheck/issues/3121)