有没有一种方法可以在没有循环的情况下使用bash搜索数组中的相同点?
所以我有一个带字符串的数组,还有另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。是否可以在不使用循环检查所有元素的情况下写入IF行?Bash现在支持关联数组,即键为字符串的数组:有没有一种方法可以在没有循环的情况下使用bash搜索数组中的相同点?,bash,loops,if-statement,Bash,Loops,If Statement,所以我有一个带字符串的数组,还有另一个字符串变量本身,我想做一个过程,当变量是数组的元素之一时。是否可以在不使用循环检查所有元素的情况下写入IF行?Bash现在支持关联数组,即键为字符串的数组: declare -A my_associative_array 因此,您可以将您的经典数组转换为关联数组,并通过一个简单的 my_string="foo bar" my_associative_array["$my_string"]="baz cux" echo "${my_associative_a
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.
Omitting the colon results in a test only for a parameter
that is unset.
因此,如果键$my_string
为null或未设置,${my_associative_array[$my_string]:+1}
扩展为空,否则扩展为1
。其余部分只是将if
bash语句与test
([]
)结合使用的经典用法:
打印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手册:
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing
is substituted, otherwise the expansion of word is substituted.
Omitting the colon results in a test only for a parameter
that is unset.
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.
Omitting the colon results in a test only for a parameter
that is unset.
因此,如果键$my_string
为null或未设置,${my_associative_array[$my_string]:+1}
扩展为空,否则扩展为1
。其余部分只是将if
bash语句与test
([]
)结合使用的经典用法:
打印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手册:
${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing
is substituted, otherwise the expansion of word is substituted.
Omitting the colon results in a test only for a parameter
that is unset.
请你也给支票写一个例子好吗?请你也给支票写一个例子好吗?