From 61841485eedbf447980964bb3bb0601b48b41fe4 Mon Sep 17 00:00:00 2001 From: Vidar Holen Date: Wed, 20 Jul 2022 08:56:52 -0700 Subject: [PATCH] Created SC2317 (markdown) --- SC2317.md | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 SC2317.md diff --git a/SC2317.md b/SC2317.md new file mode 100644 index 0000000..8653e06 --- /dev/null +++ b/SC2317.md @@ -0,0 +1,72 @@ +## Command appears to be unreachable. Check usage (or ignore if invoked indirectly). + +### Problematic code: + +```sh +usage() { + echo >&2 "Usage: $0 -i input" + exit 1 +} +if [ "$1" = "--help" ] +then + usage + exit 0 # Unreachable +fi +``` + +### Correct code: + +```sh +usage() { + echo >&2 "Usage: $0 -i input" +} +if [ "$1" = "--help" ] +then + usage + exit 0 +fi +``` + +### Rationale: + +The problematic code wanted to exit with success if the user explicitly asked for `--help`. However, since the `usage` function already had an `exit 1`, this statement could never run. + +One possible solution is to change `usage()` to only echo, and let callers be responsible for exiting. + +### Exceptions: + +ShellCheck may incorrectly believe that code is unreachable if it's invoked by variable name or in a trap. In such a case, please [[Ignore]] the message. + +Note in particular that since unreachable commands may come in clusters, it's useful to use ShellCheck's filewide or functionwide ignore directives. A `disable` directive before a function ignores the entire function: + +``` +#!/bin/bash +... +# shellcheck disable=SC2317 # Don't warn about unreachable commands in this function +start() { + echo Starting + /etc/init.d/foo start +} +"$1" +exit 0 +``` + +A disable directive after the shebang, before any commands, will ignore the entire file: +``` +#!/bin/bash +# Test script #1 +# shellcheck disable=SC2317 # Don't warn about unreachable commands in this file + +echo "Temporarily disabled" +exit 0 + +run-test1 +run-test2 +run-test3 +``` + +Defined functions are assumed to be reachable when the script ends (not exits) since another file may source and invoke them. + +### Related resources: + +* Help by adding links to BashFAQ, StackOverflow, man pages, POSIX, etc! \ No newline at end of file