Interview Prep/Shell Scripting/Arrays, conditionals and loops

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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Arrays, conditionals and loops