koalaman / shellcheck

ShellCheck, a static analysis tool for shell scripts
https://www.shellcheck.net
GNU General Public License v3.0
36.45k stars 1.78k forks source link

Shadowing `local` should throw a warning #2932

Open ChillerDragon opened 8 months ago

ChillerDragon commented 8 months ago

For new checks and feature suggestions

Here's a snippet or screenshot that shows the problem:


#!/bin/bash

args() {
        local a=a
        echo "$a"
        while true
        do
                local a
                a=b
                echo "$a"
                break
        done
        echo "$a"
}
args

it prints the following

a
b
b

If a variable is marked as local and then redefined in a sub scope as local again that sub scope can change the variable for the outer scope. Which is non obvious. And also the local in the inner scope is then completely pointless. When reading the code I would assume it prints

a
b
a

Because in the end it prints the a from the outer scope and the value was set to b in a scope that already ended.

Here's what shellcheck currently says:

Nothing

Here's what I wanted or expected to see:

Warning 'a' was already defined as local in the outer scope. The inner scope local will not have any effect.