如何检查Bash脚本中是否存在关联数组元素? [英] How can I check if an associative array element exists in my Bash script?

查看:64
本文介绍了如何检查Bash脚本中是否存在关联数组元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多动物:

declare -A animals=()
animals+=([horse])

我想检查一下动物是否存在:

and I want to check if an animal exists or not:

if [ -z "$animals[horse]"]; then
    echo "horse exists";
fi

但这不起作用.

推荐答案

bash 4.3中, -v 运算符可以应用于数组.

In bash 4.3, the -v operator can be applied to arrays.

declare -A animals
animals[horse]=neigh
# Fish are silent
animals[fish]=
[[ -v animals[horse] ]] && echo "horse exists"
[[ -v animals[fish] ]] && echo "fish exists"
[[ -v animals[unicorn] ]] && echo "unicorn does not exist" 

在以前的版本中,您需要更加小心地区分不存在的键和引用任何空字符串的键.

In prior versions, you would need to be more careful distinguishing between the key not existing and the key referring to any empty string.

animal_exists () {
    # If the given key maps to a non-empty string (-n), the
    # key obviously exists. Otherwise, we need to check if
    # the special expansion produces an empty string or an
    # arbitrary non-empty string.
    [[ -n ${animals[$1]} || -z ${animals[$1]-foo} ]]
}

animal_exists horse && echo "horse exists"
animal_exists fish && echo "fish exists"
animal_exists unicorn || echo "unicorn does not exist"

这篇关于如何检查Bash脚本中是否存在关联数组元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆