1

When defining an Array directly in the function the below works as expected;

function each {
  local array=(1 2 3)
  len=${#array[*]}
  for (( i=0; i<len; i++ )); do
    echo ${array[$i]}
  done
}

each

# outputs;

1
2
3

But I can't figure out how to pass the array in as an argument and achieve the same output;

function each {
  local array=$1
  len=${#array[*]}
  for (( i=0; i<len; i++ )); do
    echo ${array[$i]}
  done
}

array=(1 2 3)
each array

# outputs;

array

Grateful for any help, thanks.

Jamie Mason
  • 4,159
  • 2
  • 32
  • 42

1 Answers1

1

I would pass the array elements as distinct positional parameters to the function:

function f() {
    local array = "$@";
    # ...
}

## calling your function
f ("${array[@]}")
Costi Ciudatu
  • 37,042
  • 7
  • 56
  • 92