如何检查我的Bash脚本中是否存在关联数组元素?

前端之家收集整理的这篇文章主要介绍了如何检查我的Bash脚本中是否存在关联数组元素?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一系列动物:
declare -A animals=()
animals+=([horse])

我想检查动物是否存在:

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

但这不起作用.

在bash 4.3中,-v运算符可以应用于数组.
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"

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

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"
原文链接:https://www.f2er.com/bash/384746.html

猜你在找的Bash相关文章