mirror of
https://github.com/koalaman/shellcheck.git
synced 2025-10-03 19:29:44 +08:00
Created SC2312 (markdown)
37
SC2312.md
Normal file
37
SC2312.md
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
## Consider invoking this command separately to avoid masking its return value (or use '|| true' to ignore).
|
||||||
|
|
||||||
|
This is an optional suggestion enabled with `shellcheck -o check-extra-masked-returns` or `enable=check-extra-masked-returns` in a `# shellcheck` directive or `.shellcheckrc`.
|
||||||
|
|
||||||
|
### Problematic code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
set -e
|
||||||
|
cd "$(get_chroot_dir)/etc"
|
||||||
|
tar xf "$config"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Correct code:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
set -e
|
||||||
|
dir="$(get_chroot_dir)"
|
||||||
|
cd "$dir/etc"
|
||||||
|
tar xf "$config"
|
||||||
|
```
|
||||||
|
### Rationale:
|
||||||
|
|
||||||
|
In the problematic example, the exit code for `get_chroot_dir` is ignored because it is used in a command substitution in the argument of another command.
|
||||||
|
|
||||||
|
If the command shows `error: Can't determine chroot` and exits with failure without outputting a directory, then the command being run will be `cd "/etc"` and the script will proceed to overwrite the host system's configuration.
|
||||||
|
|
||||||
|
By assigning it to a variable first, the exit code of the command will propagate into the exit code of the assignment, so that it can be checked explicitly with `if` or implicitly with `set -e`.
|
||||||
|
|
||||||
|
### Exceptions:
|
||||||
|
|
||||||
|
If you don't care about the command's exit status, or already handle it through a side channel like `<(cmd; echo $? > status)`, then you can either [[ignore]] the suggestion with a directive, or use `|| true` (or `|| :`) to suppress it.
|
||||||
|
|
||||||
|
Note that this suggestion is optional, and only shows up when explicitly enabled in the script, on the command line, or in a `.shellcheckrc`.
|
||||||
|
|
||||||
|
### Related resources:
|
||||||
|
|
||||||
|
* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc!
|
Reference in New Issue
Block a user