所以我有一个字符串数组和另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。可以写一个 IF 行,而不用循环检查所有元素吗?
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
时:
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.
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句