0
所以我有一個數組與字符串,和另一個字符串變量本身,我想做一個進程,當變量是數組中的一個元素。它可以寫一個IF線,而不用循環檢查所有元素?有沒有辦法用bash搜索數組中的相同性而沒有循環?
所以我有一個數組與字符串,和另一個字符串變量本身,我想做一個進程,當變量是數組中的一個元素。它可以寫一個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
爲空或取消,${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.
你能寫一個例子來過的檢查嗎? –
完成(請參閱更新的答案)。 –
謝謝,我試試! –