测试元素是否在bash中的数组中

Tgr*_*Tgr 20 bash array

有没有一种很好的方法来检查数组是否在 bash 中有一个元素(比循环更好)?

或者,是否有另一种方法来检查数字或字符串是否等于一组预定义常量中的任何一个?

Den*_*son 27

在 Bash 4 中,您可以使用关联数组:

# set up array of constants
declare -A array
for constant in foo bar baz
do
    array[$constant]=1
done

# test for existence
test1="bar"
test2="xyzzy"

if [[ ${array[$test1]} ]]; then echo "Exists"; fi    # Exists
if [[ ${array[$test2]} ]]; then echo "Exists"; fi    # doesn't
Run Code Online (Sandbox Code Playgroud)

要最初设置数组,您还可以进行直接分配:

array[foo]=1
array[bar]=1
# etc.
Run Code Online (Sandbox Code Playgroud)

或者这样:

array=([foo]=1 [bar]=1 [baz]=1)
Run Code Online (Sandbox Code Playgroud)

  • `${array[$test1]}` 很简单,但有一个问题:如果您在脚本中使用 `set -u`(推荐),它将无法工作,因为您会得到“未绑定的变量”。 (2认同)

tok*_*and 10

这是一个老问题,但我认为最简单的解决方案还没有出现:test ${array[key]+_}. 例子:

declare -A xs=([a]=1 [b]="")
test ${xs[a]+_} && echo "a is set"
test ${xs[b]+_} && echo "b is set"
test ${xs[c]+_} && echo "c is set"
Run Code Online (Sandbox Code Playgroud)

输出:

a is set
b is set
Run Code Online (Sandbox Code Playgroud)

要查看这项工作如何检查这个

  • 信息手册建议您使用 `env` 以避免在别名、程序和其他可能采用“test”名称的函数中出现歧义。如上`env test ${xs[a]+_} && echo "a is set"`。你也可以使用双括号来获得这个功能,同样的技巧然后检查空值:`[[!-z "${xs[b]+_}" ]] && echo "b is set"` (2认同)

小智 5

有一种方法可以测试关联数组的元素是否存在(未设置),这与空不同:

isNotSet() {
    if [[ ! ${!1} && ${!1-_} ]]
    then
        return 1
    fi
}
Run Code Online (Sandbox Code Playgroud)

然后使用它:

declare -A assoc
KEY="key"
isNotSet assoc[${KEY}]
if [ $? -ne 0 ]
then
  echo "${KEY} is not set."
fi
Run Code Online (Sandbox Code Playgroud)