Skip to content

feature request: warn about local variables declared but not set inside loops #3364

@bmillwood

Description

@bmillwood

For new checks and feature suggestions

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
}
f

This 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.

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).

(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.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions