17

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[@]}"

1 Answer 1

25

Your code is almost complete. Just add shift after the assignment to $val, it will remove the first element from the $@ array.

...
val=$1
shift
arr=("$@")
...
3
  • Thank you!! Does this mean when you access an array parameter to a function, the array is all of the parameters combined? What if you wanted to pass 2 arrays to a function? Would you have to shift by the number of elements in the first array?
    – echo
    Commented Jan 5, 2018 at 15:39
  • @echo: Yes, and you'd have to pass the number, as well. If you need to pass several arrays around, better to switch to a real programming language (Perl, Python, Ruby, etc.)
    – choroba
    Commented Jan 5, 2018 at 15:45
  • Thanks a brazillion @choroba This worked great Commented Aug 19, 2022 at 21:17

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .