Since bash
4.2, the -v
conditional expression has been added. It's used to check if a variable is set (has been assigned a value). It's a useful tool when writing scripts that run under set -o nounset
, because attempting to use a non-initialized variable causes an error.
I have one issue with it, see the sample in a POSIX bash
(set -o posix
):
$ declare testvar=0
$ [ -v testvar ] && echo "It works!"
It works!
$ declare -A fizz=( [buzz]=jazz )
$ [ -v fizz[buzz] ] && echo "It works!"
It works!
$ [ -v fizz ] && echo "It doesn't work :("
$
As you can see, using -v
on a regular variable works as expected. Using it to check the presence of a field within an associative array works as expected as well. However, when checking the presence of the associative array itself, it doesn't work.
Why is that, and is there a workaround?