Bash

Check If Array Contains Element

admin by @admin ADMIN
4d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
A pure-bash membership test using `=~` or by iterating. Both are useful — pick by readability vs. speed.
Bash
Raw
arr=("alice" "bob" "carol")
target="bob"

# Method 1: explicit loop (clearest)
contains() {
    local needle="$1"; shift
    for x in "$@"; do
        [[ "$x" == "$needle" ]] && return 0
    done
    return 1
}

if contains "$target" "${arr[@]}"; then
    echo "yes"
fi

# Method 2: glue + regex (concise but tricky with separators)
[[ " ${arr[*]} " =~ " $target " ]] && echo "yes (regex)"
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.