Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array to function of shell script

Tags:

shell

How to pass array as function in shell script?
I written following code:

function test(){
param1 = $1
param2 = $2
for i in ${$param1[@]}
do
   for j in ${param2[@]}
do
       if($(i) = $(j) )
           then
           echo $(i)
           echo $(j)
       fi
done
done
}

but I am getting line 1: ${$(param1)[@]}: bad substitution

like image 359
Vivek Goel Avatar asked Dec 03 '22 02:12

Vivek Goel


1 Answers

There are multiple problems:

  • you can't have spaces around the = when assigning variables
  • your if statement has the wrong syntax
  • array passing isn't right
  • try not to call your function test because that is a shell command

Here is the fixed version:

myFunction(){
  param1=("${!1}")
  param2=("${!2}")
  for i in ${param1[@]}
  do
    for j in ${param2[@]}
    do
       if [ "${i}" == "${j}" ]
       then
           echo ${i}
           echo ${j}
       fi
    done
  done
}

a=(foo bar baz)
b=(foo bar qux)
myFunction a[@] b[@]
like image 163
dogbane Avatar answered Dec 29 '22 06:12

dogbane