あなたの投稿を読んで、文字列が配列に存在するかどうかを知りたいだけでなく(タイトルが示唆するように)、その文字列が実際にその配列の要素に対応しているかどうかを知りたいと思います。その場合は読み進めてください。
うまくいきそうな方法を見つけました。
私のように bash 3.2 をスタックしている場合に便利です (ただし、bash 4.2 でテストされ、動作しています):
array=('hello' 'world' 'my' 'name' 'is' 'perseus')
IFS=: # We set IFS to a character we are confident our
# elements won't contain (colon in this case)
test=:henry: # We wrap the pattern in the same character
# Then we test it:
# Note the array in the test is double quoted, * is used (@ is not good here) AND
# it's wrapped in the boundary character I set IFS to earlier:
[[ ":${array[*]}:" =~ $test ]] && echo "found! :)" || echo "not found :("
not found :( # Great! this is the expected result
test=:perseus: # We do the same for an element that exists
[[ ":${array[*]}:" =~ $test ]] && echo "found! :)" || echo "not found :("
found! :) # Great! this is the expected result
array[5]="perseus smith" # For another test we change the element to an
# element with spaces, containing the original pattern.
test=:perseus:
[[ ":${array[*]}:" =~ $test ]] && echo "found!" || echo "not found :("
not found :( # Great! this is the expected result
unset IFS # Remember to unset IFS to revert it to its default value
これを説明しましょう:
"${array[*]}"
この回避策は、 (二重引用符とアスタリスクに注意してください) IFS の最初の文字で区切られた配列の要素のリストに展開されるという原則に基づいています。
したがって、IFS を境界として使用したいもの (私の場合はコロン) に設定する必要があります。
IFS=:
次に、探している要素を同じ文字でラップします。
test=:henry:
そして最後に、配列でそれを探します。テストを行うために従ったルールに注意してください (すべて必須です): 配列は二重引用符で囲まれ、* が使用され (@ は適切ではありません)、IFS を以前に設定した境界文字でラップされています:
[[ ":${array[*]}:" =~ $test ]] && echo found || echo "not found :("
not found :(
存在する要素を探す場合:
test=:perseus:
[[ ":${array[*]}:" =~ $test ]] && echo "found! :)" || echo "not found :("
found! :)
別のテストでは、最後の要素 'perseus' を 'perseus smith' (スペースを含む要素) に変更して、一致するかどうかを確認することができます (一致しないはずです):
array[5]="perseus smith"
test=:perseus:
[[ ":${array[*]}:" =~ $test ]] && echo "found!" || echo "not found :("
not found :(
「perseus」自体はもはや要素ではないため、これは予想される結果です。
重要: テストが完了したら、忘れずに IFS の設定を解除して、デフォルト値 (未設定) に戻してください。
unset IFS
これまでのところ、この方法は機能しているようです。注意して、要素に含まれていないことが確実な IFS の文字を選択する必要があります。
誰にも役立つことを願っています!
よろしく、 フレッド