Skip to content

Instantly share code, notes, and snippets.

@GuyPaddock
Created July 2, 2019 03:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GuyPaddock/4f8be6d1d0bec9dad85d1d9306198b1e to your computer and use it in GitHub Desktop.
Save GuyPaddock/4f8be6d1d0bec9dad85d1d9306198b1e to your computer and use it in GitHub Desktop.
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