4

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

3 Answers 3

18

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[@]
Sign up to request clarification or add additional context in comments.

4 Comments

it is working but it is not looping . param1 only contains first index for array . param1[0]
I am calling as myFunction $p1 $p2 where $p1 size is 65
@vivek-goel i've updated my answer and added an example function call.
a=(foo bar baz) b=(foo bar qux) myFunction a[@] b[@] gives me a[@] as o/p if I echo i. currently I am using as argument=echo ${a[@]} this method is working.
0

You can use the following script accordingly

#!/bin/bash

param[0]=$1
param[1]=$2


function print_array  {
        array_name=$1
        eval echo \${$array_name[*]}
        return
}

print_array param
exit 0

Comments

0

A simple way :

function iterate 
{
  n=${#detective[@]}
  for (( i=0; i<n; i++ ))
  do
    echo ${detective[$i]}
  done
}

detective=("Feluda" "Sharlockhomes" "Bomkesh" )
iterate ${detective[@]}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.