List contains element in bash

I just came across this nice way of verifying if a list contains a specific element in bash.


containsElement () { for e in "${@:2}"; do [[ "$e" = "$1" ]] && return 0; done; return 1; }
a_list=("foo" "bar")

if containsElement "$1" "${a_list[@]}"; then
echo "$1 found in a_list!"
fi

kudos to the op of this solution : stackoverflow

Leave a comment