Passing array to function of shell script

2020-07-17 08:06发布

问题:

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

回答1:

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[@]


回答2:

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


回答3:

A simple way :

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

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


标签: shell