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.

0

1 Answer 1

1

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

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

## calling your function
f ("${array[@]}")
Sign up to request clarification or add additional context in comments.

2 Comments

thanks Costi, will close this as dupe though
I voted for closing it myself after realizing there's a complete discussion already clarifying this. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.