Warm tip: This article is reproduced from stackoverflow.com, please click
bash

Declare an empty array and distinguish it from an empty value in bash

发布于 2020-03-29 21:02:42

I need to test if certain environment variables are set before running my script. I'm using a technique from this answer:

if  [ -z ${var1+x} ]
    echo "var1 not set"
    exit 1
fi

This works well for string variables, but there's a parameter which needs to be an array. It has to be set, but could be empty.

foo=("foo" "bar" "baz")
[ -z ${foo+x} ] # false
bar=()
[ -z ${bar+x} ] # true
[ -z ${baz+x} ] # also true

So, my question is how do I declare an empty array to make it distinct from unset variable. I'd also like to test if variable is array (whether empty or not) or non array (whether set or unset).

Questioner
Denis Sheremet
Viewed
18
Ivan 2020-01-31 21:35

Or use this method

[[ ${var[@]@A} =~ '-a' ]] && echo array || echo variable

Based on this

$ man bash
...
       ${parameter@operator}
              Parameter transformation.  The expansion is either a transformation of the value of parameter or information about parameter itself, depending
              on the value of operator.  Each operator is a single letter:

              Q      The expansion is a string that is the value of parameter quoted in a format that can be reused as input.
              E      The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the $'...' quoting mechansim.
              P      The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see PROMPTING below).
              A      The  expansion  is  a string in the form of an assignment statement or declare command that, if evaluated, will recreate parameter with
                     its attributes and value.
              a      The expansion is a string consisting of flag values representing parameter's attributes.

              If parameter is @ or *, the operation is applied to each positional parameter in turn, and the expansion is the resultant list.  If  parameter
              is  an  array variable subscripted with @ or *, the case modification operation is applied to each member of the array in turn, and the expan‐
              sion is the resultant list.

              The result of the expansion is subject to word splitting and pathname expansion as described below.
...