How do you check if an element exists in an array?
IntermediateConceptArrays, conditionals and loops
Answer
contains() { # contains NEEDLE ELEMENT...
local needle=$1 e
shift
for e in "$@"; do [[ $e == "$needle" ]] && return 0; done
return 1
}
allowed=(dev staging prod)
contains "$env" "${allowed[@]}" || die "invalid env: $env"
For frequent lookups, use an associative array as a set: declare -A ok=([dev]=1 [staging]=1 [prod]=1); [[ -v ok[$env] ]]. Avoid [[ " ${arr[*]} " == *" $x "* ]], which breaks on elements with spaces.
More on Arrays, conditionals and loops
How do you declare, populate and iterate an indexed array?BeginnerWhat is the difference between `"${arr[@]}"` and `"${arr[*]}"`?IntermediateHow do associative arrays work and what are they good for in DevOps scripts?IntermediateHow do you read a command's output into an array correctly?IntermediateWhat is the difference between `[ ]`, `[[ ]]` and `(( ))`?BeginnerWhy does `[ $var = "prod" ]` fail when `var` is empty or contains spaces?Intermediate