简体   繁体   English

检查bash中是否存在关联数组元素

[英]Check if associative array element exists in bash

In a bash script, I have a locale in a variable like so在 bash 脚本中,我在变量中有一个语言环境,如下所示

locale=fr_ma

For older verions of bash ( looks like<\/a> [[ -v array[index] ]]<\/code> was introduced in version 4.3), you can use the ${var-word}<\/code> form to test is a variable has been set:对于旧版本的 bash(看起来<\/a>[[ -v array[index] ]]<\/code>是在 4.3 版中引入的),您可以使用${var-word}<\/code>形式来测试是否已设置变量:

$ zz="$RANDOM$RANDOM$RANDOM"
$ echo $zz
270502100415054
$ declare -a name
$ locale=foo

$ [[ ${name[$locale]-$zz} = "$zz" ]] && echo var is unset || echo var has a value
var is unset

$ name[$locale]=""
$ [[ ${name[$locale]-$zz} = "$zz" ]] && echo var is unset || echo var has a value
var has a value

$ [[ ${name[$locale]:-$zz} = "$zz" ]] && echo var is unset or empty || echo var has a value
var is unset or empty

-v<\/code> takes an (indexed) name<\/em> as its argument, since you are trying to determine if the expansion makes sense in the first place. -v<\/code>将(索引)名称<\/em>作为其参数,因为您首先尝试确定扩展是否有意义。

if [[ -v new_loc[$locale] ]]; then
    echo "Locale ${locale} now maps to ${new_loc[$locale]}"
fi

I managed to solve the problem by checking if the variable is not an empty string instead.我设法通过检查变量是否不是空字符串来解决问题。

Example:例子:

locale=fr_ma
declare -A new_loc
new_loc[fr_ma]=en_ma
new_loc[el_gr]=en_gr

if [[ ! -z ${new_loc[$locale]} ]]; then
    echo "Locale ${locale} now maps to ${new_loc[$locale]}"
fi

Output:输出:

Locale fr_ma now maps to en_ma

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM