In bash shell for variables:
#!/bin/bash
set -o nounset
my_var=aaa
unset var
echo "$var"
Because set
command is defined to return error if variable is not set, last line returns error:
line 6: var: unbound variable
OK, that is what I want.
Now the same thing with arrays:
#!/bin/bash
set -o nounset
my_array=(aaa bbb)
unset my_array
echo "${my_array[@]}"
But to my surprise last line does not return error. I would like bash script to return error when array is not defined.
CodePudding user response:
${my_array[@]}
is similar to $@
which is documented to be ignored by nounset
:
-u
Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion. If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.
Returning the array size is not ignored, though. Prepend the following line to make sure the array is not unset:
: ${#my_array[@]}