There are 2 problems. The first is that sh does not support arrays, so your shebang should be changed to a shell that does. (eg, #!/bin/bash). The second problem is more substantial. Arrays are not first class objects in bash (they may be in other shells but I'm going to answer the question for bash, since sh is often bash in many Linux distros and I'm using my crystal ball to determine that you meant bash when you said #!/bin/sh). You can get what you want by using eval. Change your function to something like this:
in_array(){
a=$2
eval "for i in \${$a[@]}; do
echo \$i
test $1 = \$i && return 1
done"
return 0
}
and invoke it without a '$'.
in_array home exclude_dirs
Also, I would strongly recommend inverting the return values. (return 0 if $1 appears in the array, and return 1 if it does not). Either that, or change the function name to "not_it_array". That will allow you to write things like:
if in_array home exclude_dirs; then echo home is excluded; fi
(or use a short circuiting &&). Remember that in sh, 0 is success, and non-zero is failure.
Of course, it would be easier to pass the array by passing all of the values rather than passing the name:
#!/bin/bash
in_array(){
el=$1
shift
while test $# -gt 0; do
test $el = $1 && return 0
shift
done
return 1
}
exclude_dirs=( aaa home bbb )
in_array home ${exclude_dirs[@]} && echo home is excluded