温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Declare an empty array and distinguish it from an empty value in bash
bash

其他 - 声明一个空数组,并将其与bash中的一个空值区分开

发布于 2020-03-29 21:57:39

在运行脚本之前,我需要测试是否设置了某些环境变量。我正在从这个答案中使用一种技术

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

这对于字符串变量很有效,但是有一个参数需要为数组。它必须设置,但可以为空。

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

因此,我的问题是如何声明一个空数组,以使其与未设置的变量区分开。我还想测试变量是数组(无论是否为空)或非数组(无论是设置还是未设置)。

查看更多

提问者
Denis Sheremet
被浏览
16
Ivan 2020-01-31 21:35

或使用此方法

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

基于此

$ 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.
...