Skip to content
Vidar Holen edited this page Nov 4, 2018 · 9 revisions

foo appears unused. Verify it or export it.

Problematic code:

foo=42
echo "$FOO"

Correct code:

foo=42
echo "$foo"

Rationale:

Variables not used for anything are often associated with bugs, so ShellCheck warns about them.

Also note that something like local let foo=42 does not make a let statement local -- it instead declares an additional local variable named let.

Exceptions

This warning may be falsely emitted when a variable is only referenced indirectly, and for variables that are intentionally unused.

Indirection

It's ShellCheck's intended behavior to emit this warning for any variable that is only referenced though indirection:

# foo generates a warning, even though it has five indirect references
foo=42     
name=foo
echo "${!name} $((name))"
export "$name"; eval "echo $name"
declare -n name; echo "$name"

Tracking indirect references is a common issue for compilers and static analysis tool, and it is known to be unsolvable in the most general case. There are two ways to handle unresolved indirections (which in a realistic program is by far most of them):

  • Avoid false positives by disabling all unused variable warnings.
  • Keep true positives by allowing some false positives.

ShellCheck intentionally chooses the latter. For consistency and to avoid giving the impression that it should work more generally, it does not attempt to resolve even indirections that seem trivial, like the above.

If you have variables that will not have direct references, consider using an associative array in bash, or just Ignore the warning. You can do this for individual variables, sets of variables, the whole script, or all scripts.

Intentionally unused variables

For throwaway variables, consider using _ as a dummy:

read _ last _ zip _ _ <<< "$str"
echo "$last, $zip"

or if you prefer to keep the names, use a directive to disable the warning:

# shellcheck disable=SC2034  # Unused variables left for readability
read first last email zip lat lng <<< "$str"
echo "$last, $zip"

ShellCheck

Each individual ShellCheck warning has its own wiki page like SC1000. Use GitHub Wiki's "Pages" feature above to find a specific one, or see Checks.

Clone this wiki locally