How to write a function, in_array
, that checks if a specified array contains a specified value
The function should take two arguments:
array_name
– the name of the arrayvalue
– the value to test for
With this test harness:
colors=(red green yellow "royal blue")
test() {
local answer=no
if in_array colors "$1"; then
answer=yes
fi
printf "%-13s %s\n" "$1" "$answer"
}
test red
test green
test "royal blue"
test blue
the following output should be produced:
red yes
green yes
royal blue yes
blue no
Edit: The essence of this question is that the function must have no hard-coded dependency on the array. I will consider all functions that satisfy this requirement and produce the shown output for the shown array.