-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Description
For new checks and feature suggestions
- https://www.shellcheck.net/ (i.e. the latest commit) currently gives no useful warnings about this
- I searched through https://github.com/koalaman/shellcheck/issues and didn't find anything related
- the keywords I tried: local unset uninitialised uninitialized
Here's a snippet or screenshot that shows a potential problem:
#!/usr/bin/env bash
function f() {
for i in a b c; do
local v
[ "$i" == b ] && v=true
echo "$i: $v"
done
}
fThis code outputs:
a:
b: true
c: true
I polled some people I know and they frequently guessed the last line incorrectly -- they might expect that after declaring local v they're guaranteed that v is unset, but in a loop that's not true.
- See fix patchShebangs in the presence of readonly scripts NixOS/nixpkgs#462319 for a bug I found in the wild that stemmed from believing that if you'd just done a
localvariable declaration, it must have an unset value.
Here's what shellcheck currently says:
No issues detected!
Here's what I wanted to see:
A new warning that v is function-local, not loop-local, and since it's uninitialised at the declaration site it can retain values across loop iterations. Should recommend either that the variable is declared local outside the loop or that it's initialised at the declaration. For extra credit, don't produce a warning if the variable is clearly set after the declaration before it can possibly be used (i.e. local v; v=x is equivalent to local v=x and doesn't trigger the warning).
- See fix patchShebangs in the presence of readonly scripts NixOS/nixpkgs#462319 for a bug I found in the wild that stemmed from believing that if you'd just done a
localvariable declaration, it must have an unset value.
(I think it's very possible that this is one instance of a more general phenomenon of people not understanding how local works, and there's a better warning that would have caught the aforementioned bug. But wanted to start a conversation about it regardless.)