Is there a way to test whether an array contains a specified element?
e.g., something like:
array=(one two three)
if [ \"one\" in ${array} ]; then
...
f
Try this:
array=(one two three)
if [[ "${array[*]}" =~ "one" ]]; then
echo "'one' is found"
fi
if you just want to check whether an element is in array, another approach
case "${array[@]/one/}" in
"${array[@]}" ) echo "not in there";;
*) echo "found ";;
esac
A for loop will do the trick.
array=(one two three)
for i in "${array[@]}"; do
if [[ "$i" = "one" ]]; then
...
break
fi
done
I got an function 'contains' in my .bashrc-file:
contains ()
{
param=$1;
shift;
for elem in "$@";
do
[[ "$param" = "$elem" ]] && return 0;
done;
return 1
}
It works well with an array:
contains on $array && echo hit || echo miss
miss
contains one $array && echo hit || echo miss
hit
contains onex $array && echo hit || echo miss
miss
But doesn't need an array:
contains one four two one zero && echo hit || echo miss
hit
OPTIONS=('-q','-Q','-s','-S')
find="$(grep "\-q" <<< "${OPTIONS[@]}")"
if [ "$find" = "${OPTIONS[@]}" ];
then
echo "arr contains -q"
fi
I like using grep for this:
if echo ${array[@]} | grep -qw one; then
# "one" is in the array
...
fi
(Note that both -q
and -w
are non-standard options to grep: -w
tells it to work on whole words only, and -q
("quiet") suppresses all output.)