Is there a way to pass an array to a function as one of its parameters?
Currently I have
#!/bin/bash
highest_3 () {
number_under_test=(${array[@]})
max_of_3=0
for ((i = 0; i<$((${#number_under_test[@]}-2)); i++ )) {
test=$((number_under_test[i] +
number_under_test[i+1] +
number_under_test[i+2]))
if [ $test -gt $max_of_3 ]; then
max_of_3=$((number_under_test[i]+
number_under_test[i+1]+
number_under_test[i+2]))
result=$((number_under_test[i]))$((number_under_test[i+1]))$((number_under_test[i+2]))
fi
}
}
array=(1 2 3 4 5 6 7 8 7 6 5 4 3 2 1)
highest_3
echo result=$result
array=(1 2 3 4 3 2 1)
highest_3
echo result=$result
which works by just setting array
and using array
, but is there a way to pass in the array, e.g. (1 2 3 4 5 4 3 2 1) as an actual parameter rather than just setting a (presumably global) variable?
Update: I'd like to be able to pass in other parameters beside this array
${#array[@]}
results to 15 elements, but in foo()${#_array[@]}
shows just 1 element. See also here. – Joe Sep 21 '17 at 16:36