Ideally you would want to use an array to store the names and iterate over it to test for a match:
#!/bin/bash
contains()
{
local element
for element in "${@:2}"; do
[ "${element}" = "$1" ] && return 0
done
return 1
}
a=(tom jerry albert yoyo)
for name in tom to foo; do
if contains "${name}" "${a[@]}"; then
echo "${name} matches"
else
echo "${name} doesn't match"
fi
done
$ ./t.sh
tom matches
to doesn't match
foo doesn't match
You could even pass by "reference" by using variable indirection, that way you only have to pass the name of the array to contains
which you want to match against:
contains()
{
local element
for element in "${!1}"; do
[ "${element}" = "$2" ] && return 0
done
return 1
}
names=(tom jerry albert yoyo)
for name in tom to foo; do
if contains "names" "${name}"; then
echo "${name} matches"
else
echo "${name} doesn't match"
fi
done