測試 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

相關內容