bash で要素が配列内にあるかどうかをテストする

bash で要素が配列内にあるかどうかをテストする

bash で配列に要素があるかどうかを確認する良い方法はありますか (ループするよりも良い方法)?

あるいは、数値または文字列が定義済み定数のセットのいずれかと等しいかどうかを確認する別の方法はありますか?

答え1

Bash 4 では、連想配列を使用できます。

# set up array of constants
declare -A array
for constant in foo bar baz
do
    array[$constant]=1
done

# test for existence
test1="bar"
test2="xyzzy"

if [[ ${array[$test1]} ]]; then echo "Exists"; fi    # Exists
if [[ ${array[$test2]} ]]; then echo "Exists"; fi    # doesn't

配列を最初に設定するには、直接割り当てを行うこともできます。

array[foo]=1
array[bar]=1
# etc.

またはこのように:

array=([foo]=1 [bar]=1 [baz]=1)

答え2

これは古い質問ですが、最も簡単な解決策はまだ出ていないと思います。test ${array[key]+_}例:

declare -A xs=([a]=1 [b]="")
test ${xs[a]+_} && echo "a is set"
test ${xs[b]+_} && echo "b is set"
test ${xs[c]+_} && echo "c is set"

出力:

a is set
b is set

この仕組みを確認するにはこれ

答え3

連想配列の要素が存在するかどうか(設定されていないかどうか)をテストする方法があります。これは空とは異なります。

isNotSet() {
    if [[ ! ${!1} && ${!1-_} ]]
    then
        return 1
    fi
}

次にそれを使用します:

declare -A assoc
KEY="key"
isNotSet assoc[${KEY}]
if [ $? -ne 0 ]
then
  echo "${KEY} is not set."
fi

答え4

#!/bin/bash
function in_array {
  ARRAY=$2
  for e in ${ARRAY[*]}
  do
    if [[ "$e" == "$1" ]]
    then
      return 0
    fi
  done
  return 1
}

my_array=(Drupal Wordpress Joomla)
if in_array "Drupal" "${my_array[*]}"
  then
    echo "Found"
  else
    echo "Not found"
fi

関連情報