I want to create a function in bash that takes 2 parameters. One is simply a value and the other is an array. I would loop over the array and perform an operation using both the array element, and the other function parameter. It would be something like this (I don't know the proper syntax):
#!/bin/bash
function sumOverArray() {
val=$1
arr=("$@")
for i in "${arr[@]}";
do
sum=$((i + val))
echo "sum: $sum"
done
}
array=(1 2 3)
sumOverArray 3 "${array[@]}"
Best Answer
Your code is almost complete. Just add
shift
after the assignment to$val
, it will remove the first element from the$@
array.