From aeadbd894881b8022dfe52805575c063577224f1 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Sat, 2 Oct 2021 13:17:36 -0700 Subject: [PATCH] Created SC2312 (markdown) --- SC2312.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 SC2312.md diff --git a/SC2312.md b/SC2312.md new file mode 100644 index 0000000..49e792b --- /dev/null +++ b/SC2312.md @@ -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! \ No newline at end of file