When I set nullglob in bash:
shopt -s nullglob
and then declare an associative array:
declare -A arr=( [x]=y )
I cannot unset specific keys within the array:
unset arr[x]
echo ${#arr[@]} # still 1
However, unsetting nullglob makes this operation work like I expect:
shopt -u nullglob
unset arr[x]
echo ${#arr[@]} # now it's 0; x has been removed
What's going on here? I don't see how shell globbing could be relevant to the situation. I've tested this on bash 4.4.19 and 5.0.0.
This can be explained by reference the the
bashdocumentation (themanpage), paraphrased here:In other words,
nullglobaffects what will happen to yourarr[x]argument. It will either be left alone or removed.You can see this effect by turning on echo-before-execute flag with
set -x:Note that this is the "word is removed" case. The "word is left unchanged" case is show thus:
That final echoed command above also provides a clue as to how to delete an entry if you have enable
nullglob. Just quote the argument to prevent expansion:This will work regardless of the
nullglobsetting, because of the section regarding quoting in the documentation: