Skip to content

Array Contains a Value

Return success if a Bash nameref array contains a given value, or failure if the value is missing, without expanding the array yourself.

Language: Shell

Added on: 18th August 2026

array_contains() {
  local -n haystack=$1
  local needle=$2

  for i in "${haystack[@]}"; do
    if [[ $i == "${needle}" ]]; then
      return 0
    fi
  done

  return 1
}

Caveats

Needs Bash namerefs (Bash 4.3+). Pass the array name, not an expansion.