Created
July 2, 2019 03:38
-
-
Save GuyPaddock/4f8be6d1d0bec9dad85d1d9306198b1e to your computer and use it in GitHub Desktop.
Check if a value is in an array in Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## | |
# 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