Teste se o elemento está no array no bash

Teste se o elemento está no array no bash

Existe uma boa maneira de verificar se um array possui um elemento no bash (melhor do que fazer um loop)?

Alternativamente, existe outra maneira de verificar se um número ou string é igual a algum conjunto de constantes predefinidas?

Responder1

No Bash 4, você pode usar arrays associativos:

# 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

Para configurar o array inicialmente você também pode fazer atribuições diretas:

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

ou desta forma:

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

Responder2

É uma questão antiga, mas acho que ainda não apareceu qual a solução mais simples: test ${array[key]+_}. Exemplo:

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"

Saídas:

a is set
b is set

Para ver como isso funciona, verifiqueesse.

Responder3

Existe uma maneira de testar se existe um elemento de um array associativo (não definido), isso é diferente de vazio:

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

Então use-o:

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

Responder4

#!/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

informação relacionada