Skip to main content

How to Check if Value Exists in Array

• 2 min read
bash array element search conditional data structures

Quick Answer: Check if Value Exists in Array

To check if a value exists in an array, use a loop: for item in "${array[@]}"; do [[ "$item" = "$search" ]] && found=1; done. Or more concisely with grep: printf '%s\n' "${array[@]}" | grep -q "^value$". The loop method is most portable.

Quick Comparison: Array Search Methods

MethodSyntaxSpeedPortabilityBest For
for loopfor item in...MediumExcellentSimple search
grepprintf '%s\n' | grepMediumExcellentPattern search
Case statementcase $var in...FastExcellentLimited values

Bottom line: Use for loop for reliability; use grep for pattern matching.


Check if a value exists in an array using loops, conditional expressions, and helper functions.

Method 1: Check with Loop

#!/bin/bash

array=("apple" "banana" "cherry" "date")
search="banana"

found=0
for item in "${array[@]}"; do
  if [ "$item" = "$search" ]; then
    found=1
    break
  fi
done

if [ $found -eq 1 ]; then
  echo "Found: $search"
else
  echo "Not found: $search"
fi

Using Case Statement

#!/bin/bash

array=("apple" "banana" "cherry")
search="banana"

case "${array[@]}" in
  *"$search"*) echo "Found" ;;
  *) echo "Not found" ;;
esac

Function to Check Existence

#!/bin/bash

array_contains() {
  local array=("$@")
  local search="${array[-1]}"
  unset 'array[-1]'

  for item in "${array[@]}"; do
    if [ "$item" = "$search" ]; then
      return 0
    fi
  done
  return 1
}

# Usage
myarray=("apple" "banana" "cherry")

if array_contains "${myarray[@]}" "banana"; then
  echo "Found"
else
  echo "Not found"
fi

Check with Index

#!/bin/bash

array=("apple" "banana" "cherry")

# Get index of element
index=-1
for i in "${!array[@]}"; do
  if [ "${array[$i]}" = "banana" ]; then
    index=$i
    break
  fi
done

if [ $index -ge 0 ]; then
  echo "Found at index: $index"
else
  echo "Not found"
fi

Using Grep with Array

# Check if value exists using grep
if echo "${array[@]}" | grep -q "search_term"; then
  echo "Found"
fi

Associative Array Lookup

#!/bin/bash

# Faster lookup with associative array
declare -A map
map["apple"]="fruit"
map["banana"]="fruit"
map["carrot"]="vegetable"

if [ -n "${map[apple]}" ]; then
  echo "apple exists: ${map[apple]}"
fi

# Check if key exists
if [ -n "${map[orange]}" ]; then
  echo "Found"
else
  echo "Not found"
fi

Case-Insensitive Match

#!/bin/bash

array=("Apple" "Banana" "Cherry")
search="apple"

for item in "${array[@]}"; do
  if [ "${item,,}" = "${search,,}" ]; then
    echo "Found (case-insensitive): $item"
    break
  fi
done

Partial Match

#!/bin/bash

array=("apple pie" "banana split" "cherry tart")
search="apple"

for item in "${array[@]}"; do
  if [[ "$item" =~ $search ]]; then
    echo "Found: $item"
    break
  fi
done

Count Occurrences

#!/bin/bash

array=("apple" "banana" "apple" "cherry" "apple")
search="apple"

count=0
for item in "${array[@]}"; do
  if [ "$item" = "$search" ]; then
    ((count++))
  fi
done

echo "Count: $count"

Return All Matches

#!/bin/bash

find_all() {
  local search="$1"
  shift
  local array=("$@")

  local matches=()
  for i in "${!array[@]}"; do
    if [ "${array[$i]}" = "$search" ]; then
      matches+=("$i")
    fi
  done

  echo "${matches[@]}"
}

# Usage
array=("apple" "banana" "apple" "cherry")
indices=$(find_all "apple" "${array[@]}")
echo "Found at indices: $indices"

Performance Comparison

For large arrays, use associative arrays for O(1) lookup instead of linear search O(n).

Common Mistakes

  1. Not quoting array: "${array[@]}" not ${array[@]}
  2. String vs exact match: Use = for exact, =~ for pattern
  3. Unset variables: Variables must be initialized
  4. Case sensitivity: = is case-sensitive

Key Points

  • Use loop with break for simple check
  • Use function for reusable code
  • Use associative array for fast lookup
  • Quote variables properly
  • Handle empty arrays

Summary

Checking array membership is common. Use loops for small arrays, associative arrays for fast lookup on large datasets, and regex for pattern matching.