2015-06-10 14 views

cevap

3

BASH size yapabilirsiniz: horse dizideki geçerli bir endeksidir foobar eğer

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

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

"${animals[horse]+foobar}" döner, aksi takdirde hiçbir şey döndürür.

+0

Maalesef ... ne anlama geliyor '=' çizgi "hayvanlar + = ([at] =)" sonunda – sensorario

+0

endeksi 'horse' boş bir değer atama olduğunu That. hayvanlar + = ([at]) aksi takdirde sözdizimi hatası verecektir. – anubhava

8

komut dosyanızda birkaç yazım hataları vardır

olduğu gibi bunu çalıştırdığınızda, ben olsun BASH aşağıdaki hata iletileri:

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

birincisi diyor sen horse kullanmak istiyorsanız Bir ilişkisel dizi için bir indeks olarak, ona bir değer atamanız gerekir. Boş bir değer (boş) tamam.

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

İkinci mesaj

, köşeli ayraç değerin bir kısmını kabul edilir Son olarak boşluk

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

ayrılmış değil eğer, test etmek istediğiniz değeri ve braket ayırmak gerektiğini söylüyor ilişkilendirilmiş bir dizideki bir öğe, kendisine atanan bir değer olduğunda (bu değer boş olsa bile) bulunur. Bir dizi değer zaten answered on this site olmuştur ayarlanırsa test sorusu, biz çözüm burada convinience için

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

ödünç alabilir komple script:

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

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

Çok sayıda unsuru bir kerede tanımlamak istemedikçe 'hayvanlar [at] =' kullanmaktan çok daha basittir + = ' – chepner

+0

@chepner yeterlidir. –

9

bash 4.3'te -v operatörü dizilere uygulanabilir. önceki sürümlerinde

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" 

, mevcut değil anahtarı ve herhangi boş bir dizeye atıfta anahtarın ayırt daha dikkatli olmak gerekir.

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" 
İlgili konular