Skip to main content

This bash function helps find if a non-associative array has an item. It returns "1" if the item is in the array, and "0" if it is not.

#!/usr/bin/env bash

##
# Check if item is in array
# https://raymii.org/s/snippets/Bash_Bits_Check_If_Item_Is_In_Array.html
##

in_array() {
    local haystack=${1}[@]
    local needle=${2}
    for i in ${!haystack}; do
        if [[ ${i} == ${needle} ]]; then
            return 0
        fi
    done
    return 1
}

#
# Usage
#

declare -a vpsservers=("vps1" "vps2" "vps3" "vps4" "vps6");

in_array vpsservers vps3 && echo "found" || echo "not found"
in_array vpsservers vps5 && echo "found" || echo "not found"
# 1. >> found
# 2. >> not found