-`unset2` is only really needed once. We remain 5 levels deep in
`f`\'s for the remaining `unset` calls, which peel away the outer
layers of `a`\'s.
- Notice that the \"a\" is unset using an ordinary unset command at
recursion depth 1, and subsequently calling unset reveals a again in
the global scope, which has since been modified in a lower scope
using declare -g.
- Declaring a global with declare -g bypasses all locals and sets or
modifies the variable of the global scope (outside of all
functions). It has no affect on the visibility of the global.
- This doesn\'t apply to individual array elements. If two local
arrays of the same name appear in different scopes, the entire array
of the inner scope needs to be unset before any elements of the
outer array become visible. This makes \"unset\" and \"unset2\"
identical for individual array elements, and for arrays as a whole,
unset and unset2 behave as they do for scalar variables.
### Args
Like several other Bash builtins that take parameter names, unset
expands its arguments.
~ $ ( a=({a..d}); unset 'a[2]'; declare -p a )
declare -a a='([0]="a" [1]="b" [3]="d")'
As usual in such cases, it\'s important to quote the args to avoid
accidental results such as globbing.
~ $ ( a=({a..d}) b=a c=d d=1; set -x; unset "${b}["{2..3}-c\]; declare -p a )
+ unset 'a[2-1]' 'a[3-1]'
+ declare -p a
declare -a a='([0]="a" [3]="d")'
Of course hard to follow indirection is still possible whenever
arithmetic is involved, also as shown above, even without extra
expansions.
In Bash, the `unset` builtin only evaluates array subscripts if the
array itself is set.
~ $ ( unset -v 'a[$(echo a was set >&2)0]' )
~ $ ( a=(); unset -v 'a[$(echo a was set >&2)0]' )
a was set
## Portability considerations
Quoting POSIX:
If neither -f nor -v is specified, name refers to a variable; if a variable by that name does not exist, it is unspecified whether a function by that name, if any, shall be unset.
Therefore, it is recommended to explicitly specify `-f` or `-v` when
using `unset`. Also, I prefer it as a matter of style.