2017-08-11 24 views

回答

3

猛砸現在支持關聯數組,即數組哪些鍵是字符串:

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. 
+0

你能寫一個例子來過的檢查嗎? –

+0

完成(請參閱更新的答案)。 –

+0

謝謝,我試試! –

相關問題