Updated SC2034 (markdown)

Vidar Holen
2018-11-04 14:09:04 +08:00
parent 43fbad5d14
commit 0133da666d

@@ -22,7 +22,29 @@ Also note that something like `local let foo=42` does not make a `let` statement
### Exceptions ### Exceptions
ShellCheck may not always realize that the variable is in use (especially with indirection), and may not realize you don't care (with throwaway variables or unimplemented features). 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: For throwaway variables, consider using `_` as a dummy:
@@ -31,22 +53,10 @@ read _ last _ zip _ _ <<< "$str"
echo "$last, $zip" echo "$last, $zip"
``` ```
or use a directive to disable the warning: or if you prefer to keep the names, use a directive to disable the warning:
```sh ```sh
# shellcheck disable=SC2034 # shellcheck disable=SC2034 # Unused variables left for readability
read first last email zip lat lng <<< "$str" read first last email zip lat lng <<< "$str"
echo "$last, $zip" echo "$last, $zip"
``` ```
For indirection, there's not much you can do without rewriting to use arrays or similar:
```sh
bar=42 # will always appear unused
foo=bar
echo "${!foo}"
```
This is expected behavior, and not a bug. There is no good way to statically analyze indirection in shell scripts, just like static C analyzers have a hard time preventing segfaults.
As always, there are ways to [[ignore]] this and other messages if they frequently get in your way.