3

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.

1 Answer 1

2

${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[@]}
Sign up to request clarification or add additional context in comments.

5 Comments

This seems consistent with the observed behavior, but where is it documented that the ${my_array[@]} form has this property?
Prior to Bash 4.4 "${my_array[@]}" produced an error when the array was defined but empty and nounset was set. That was a bug. It looks like they over-compensated when they fixed the empty array problem in 4.4. I think the new behaviour is a bug. It's not so bad a bug because there are several holes in the nounset checks anyway.
What does "colon" means before command?
Colon is a builtin that does nothing, see man bash.
It is something similar like: true ${#my_array[@]} but ":" is shell build in and true is separate program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.