Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Check if a value is in an array in Bash
##
# Determine if a given element exists in an array.
#
# Based on:
# https://stackoverflow.com/a/11525897/4342230
#
# @param string $1
# The value to look for (the "needle").
# @param string... $2...
# The array of values to search (the "haystack").
#
# @return int
# Either success (0) if the needle was found in the haystack; or, 1 if it was
# not.
#
array_contains() {
local needle="${1}"; shift
local haystack=( "${@}" )
for current_element in "${haystack[@]}"; do
if [[ "${current_element}" == "${needle}" ]]; then
return 0
fi
done
return 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.