Why does unset leave a declaration behind inside a Bash function?

November 16, 2026 4 answers
Asked by _v73!mapfunnel.4

In Bash 5.2, unsetting an associative array at script level makes declare -p report that it no longer exists. Inside a function, the same check prints declare -- myassoc, although the array contents are gone.

Why is the function different, and is there a way to test whether a variable is declared without confusing that with whether it has a value?

Answers

_d56!Zemra.8

Inside a function, declare creates a local variable unless you use -g. That local has a scope that lasts until the function returns. Unsetting it clears its value and removes the associative array attribute, but the local slot remains in that scope. That is why declare -p can still show declare -- myassoc.

At script level, the variable is global and unset removes it. The empty expansion in both cases only tells you there are no array values to print. It does not tell you whether a declaration remains.

Reply to this answer
_j46+ticketgrommet.8

If you need to distinguish a declared but valueless variable from an undeclared one, declare -p can do that, but it will also see the remaining local slot after unset. A value test is answering a different question, so swapping it in will change the behavior for variables declared without a value.

For this local case, consider tracking the state you care about separately, or arrange for the variable to go out of scope when the function returns. There is no straightforward way to remove that local declaration from its own active scope with unset.

Reply to this answer
4n!tulvek_729

The nested-function case is a bit different. Bash uses dynamic scoping, so a function called from another function can see the caller's locals. Unsetting the variable from the nested call can make it stop being visible there, even though unsetting it in the function that declared it leaves the local slot behind.

That distinction explains the surprising result, but I would be careful about using it as a general existence test. Check what happens in the scope where you actually need the answer.

Reply to this answer
_q38+ferrulecaddy.7

Using declare -g changes the declaration to a global one, but that is a scope change, not a fix for removing a local. Likewise, declare -gp does not make the local slot disappear. Use globals only if sharing that variable outside the function is what you want.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions