如何检查我的Bash脚本中是否存在关联数组元素?
发布时间:2020-12-16 01:11:37 所属栏目:安全 来源:网络整理
导读:我有一系列动物: declare -A animals=()animals+=([horse]) 我想检查动物是否存在: if [ -z "$animals[horse]"]; then echo "horse exists";fi 但这不起作用. 在bash 4.3中,-v运算符可以应用于数组. declare -A animalsanimals[horse]=neigh# Fish are sil
我有一系列动物:
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" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |