我有一系列动物:
declare -A animals=() animals+=([horse])
我想检查动物是否存在:
if [ -z "$animals[horse]"]; then echo "horse exists"; fi
但这不起作用.
在bash 4.3中,-v运算符可以应用于数组.
原文链接:https://www.f2er.com/bash/384746.htmldeclare -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"