2015-06-10 37 views

回答

3

在bash,你可以這樣做:

declare -A animals=() 
animals+=([horse]=) 

[[ "${animals[horse]+foobar}" ]] && echo "horse exists" 

"${animals[horse]+foobar}"回報foobar如果horse是在陣列中的有效指標,否則將沒有返回值。

+0

對不起,......什麼意思'='在行「動物+ =([馬] =)」結束 – sensorario

+0

這是一個空值指數'horse'的分配。 '動物+ =([馬])'否則會給語法錯誤。 – anubhava

8

有在腳本中一些錯別字

當我運行它,因爲它是,我從BASH以下錯誤消息:

1. animals: [horse]: must use subscript when assigning associative array 
2. [: missing `]' 

第一個說,如果你想使用horse作爲關聯數組的索引,您必須爲其分配一個值。一個空值(空)是可以的。

-animals+=([horse]) 
+animals+=([horse]=) 

第二個消息說,你必須要測試的價值和支架分開,因爲方括號被認爲是值的一部分,如果沒有空間

-if [ -z "$animals[horse]"]; then 
+if [ -z "$animals[horse]" ]; then 

分離最後,當存在賦值給它的值時,存在關聯數組中的元素(即使此值爲空)。彷彿一個數組值設置已經被answered on this site測試的問題,我們可以借用解決方案

-if [ -z "$animals[horse]"]; then 
+if [ -n "${animals[horse]+1}" ]; then 

爲了您的舒適這裏是完整的腳本:

declare -A animals=() 
animals+=([horse]=) 

if [ -n "${animals[horse] + 1}" ]; then 
    echo "horse exists"; 
fi 
+4

除非OP想要一次定義多個元素,否則編寫'動物[馬] ='要比使用+ =' – chepner

+0

@chepner要簡單得多。 –

9

bash 4.3 ,-v運算符可以應用於數組。

declare -A animals 
animals[horse]=neigh 
# Fish are silent 
animals[fish]= 
[[ -v animals[horse] ]] && echo "horse exists" 
[[ -v animals[fish] ]] && echo "fish exists" 
[[ -v animals[unicorn] ]] && echo "unicorn does not exist" 

在之前的版本中,您需要更小心地區分不存在的鍵和引用任何空字符串的鍵。

exists() { 
    # If the given key maps to a non-empty string (-n), the 
    # key obviously exists. Otherwise, we need to check if 
    # the special expansion produces an empty string or an 
    # arbitrary non-empty string. 
    [[ -n ${animal[$1]} || -z ${animal[$1]-foo} ]] 
} 

exists horse && echo "horse exists" 
exists fish && echo "fish exists" 
exists unicorn || echo "unicorn does not exist"