【发布时间】:2017-08-11 07:46:35
【问题描述】:
所以我有一个带有字符串的数组,以及另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。是否可以写一个 IF 行,而不用循环检查所有元素?
【问题讨论】:
标签: bash loops if-statement
所以我有一个带有字符串的数组,以及另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。是否可以写一个 IF 行,而不用循环检查所有元素?
【问题讨论】:
标签: bash loops if-statement
Bash 现在支持关联数组,即键为字符串的数组:
declare -A my_associative_array
因此,您可以将您的经典数组转换为关联数组,并通过简单的方式访问您正在寻找的条目:
my_string="foo bar"
my_associative_array["$my_string"]="baz cux"
echo "${my_associative_array[$my_string]}"
echo "${my_associative_array[foo bar]}"
并测试密钥的存在:
if [ "${my_associative_array[$my_string]:+1}" ]; then
echo yes;
else
echo no;
fi
来自 bash 手册:
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing
is substituted, otherwise the expansion of word is substituted.
因此,如果键 $my_string 为 null 或未设置,${my_associative_array[$my_string]:+1} 扩展为空,否则扩展为 1。其余的只是if bash 语句结合test ([]) 的经典用法:
if [ 1 ]; then echo true; else echo false; fi
打印true while:
if [ ]; then echo true; else echo false; fi
打印false。如果您更愿意将空条目视为任何其他现有条目,只需省略冒号:
if [ "${my_associative_array[$my_string]+1}" ]; then
echo yes;
else
echo no;
fi
来自 bash 手册:
Omitting the colon results in a test only for a parameter
that is unset.
【讨论】: