-2

I'm creating a function in shell script and I need to pass 2 parameters. One is the path and the another is an array. But the problem is the second parameter is getting the content of the first parameter.

Ex.:

input_files_path="./path"
array=("Word1" "Word2" "Word3")

list_files(){
  path=$1
  array_in=("${@}")

  echo "${array_in[@]}"

}

list_files "${input_files_path}" "${array[@]}"

Ouput:

./path Word1 Word2 Word3

If I change the second parameter to

array_in=$2

it doesn't work.

Cyrus
  • 84,225
  • 14
  • 89
  • 153

1 Answers1

0

When you call a function with parameters, the fact you assign one parameter to a variable does not remove it form the parameters list.

What you need to do is assign the first parameter to a variable, then use shift to remove the argument from the arguments list. Then when you use @, it will no longer include the first parameter.

Like this:

#!/bin/bash

input_files_path="./path"
array=("Word1" "Word2" "Word3")

list_files(){
  path=$1
  # remove the $1 argument from $@
  shift
  array_in=("${@}")

  echo "${array_in[@]}"

}

list_files "${input_files_path}" "${array[@]}"
Nic3500
  • 8,144
  • 10
  • 29
  • 40