r/bash • u/da_Aresinger • 16h 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[@]}"
OUTPUT:
./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
OUTPUT:
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 REALLY insane:
```Bash bar () { declare -A myassoc myassoc[key]="Hello World"
declare -p myassoc
echo "This should not be empty: ${myassoc[@]}"
foo () {
unset myassoc
echo "In foo:"
declare -p myassoc
echo "This should be empty: ${myassoc[@]}"
}
foo
echo "After foo:"
declare -p 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:
Bash
OUTPUT:
declare -A myassoc=([key]="Hello World" )
This should not be empty: Hello World
In foo:
/home/pi/bash_experiments/./unsetLocalVar: line 12: declare: myassoc: not found
This should be empty:
After foo:
/home/pi/bash_experiments/./unsetLocalVar: line 17: declare: myassoc: not found
This should be empty:
The solution is to wrap the unset in a nested function.
