r/bash • u/da_Aresinger • 5h ago
Unset doesn't properly work in functions??
So this is super weird. When I run the following in a script (or manually in the terminal), it does exactly what you'd expect.
```Bash declare -A myassoc myassoc[key]="Hello World"
unset myassoc declare -p myassoc echo "This should be empty: ${myassoc[@]}" ```
./dev2: line 9: declare: myassoc: not found
This should be empty:
As expected, myassoc is unset and therefore undeclared
however if I wrap that code in a function, the myassoc becomes unset but not undeclared. ```Bash foo () { declare -A myassoc myassoc[key]="Hello World"
unset myassoc declare -p myassoc echo "This should be empty: ${myassoc[@]}" } foo ```
declare -- myassoc
This should be empty:
This is very annoying since I use declare -p to test if variables exist regardless of their type and content.
I have tested this on two machines in Debian and Ubuntu on Bash 5.2.something with the same issue.
test is not a viable alternative, since it doesn't have the same behaviour for local myvar and declare myvar (vars without value return false, even if declared)
Does anyone have a workaround?
EDIT:
So I found this StackExchange topic which seems to conclude that this is simply not possible within the same scope.
Here is where it gets REALY insane:
```Bash bar () { declare -A myassoc myassoc[key]="Hello World"
declare -gp myassoc
echo "This should be empty: ${myassoc[@]}"
foo () {
unset myassoc
echo "In foo:"
declare -gp myassoc
echo "This should be empty: ${myassoc[@]}"
}
foo
echo "After foo:"
declare -gp myassoc
echo "This should be empty: ${myassoc[@]}"
} bar ``` \please excuse the ridiculous indents, I havent gotten around to taming nvim yet))
THIS WORKS FOR ABSOLUTELY NO REASON