Home > other >  How to pass multiple arrays to function in shell script and how to access it in the function
How to pass multiple arrays to function in shell script and how to access it in the function

Time:11-04

I am new in shell script,

I want to pass two string arrays to function as an argument and want to access that in the function for further operation.

Please help me in that.

Thank you.

CodePudding user response:

When you pass one or array to the function, it actually passes each element as an argument. You can retrieve them all from $@
If you know the size of each array, you can split them by the size. Otherwise, you need some tricky methods to split the arrays. For example, pass another parameter which will never present in these arrays.
Here is an example.

#!/bin/bash

func()
{
  echo "all params: $@"
  echo "para size: ${#@}"
  p1=()
  p2=()
  i=1
  for e in "${@}" ; do
    if [[ "$e" == "|" ]] ; then
      i=$(($i 1))
      continue
    fi
    if [ $i -eq 1 ] ; then
      p1 =($e)
    else
      p2 =($e)
    fi
  done
  echo "p1: ${p1[@]}"
  echo "p2: ${p2[@]}"
}

a=(1 2 3 4 5)
b=('a' 'b' 'c')
func "${a[@]}" "|" "${b[@]}"

This is the output of the script.

$ ./test.sh
all params: 1 2 3 4 5 | a b c
para size: 9
p1: 1 2 3 4 5
p2: a b c

CodePudding user response:

Bash isn't great at handling array passing to functions, but it can be done. What you will need to pass is 4 parameters: number-of-elements-array1 array1 number-of-elements-array2 array2. For example, you can do:

#!/bin/bash

myfunc() {
  local nelem1=$1               ## set no. elements in array 1
  local -a array1
  local nelem2
  local -a array2
  
  shift                         ## skip to next arg
  while ((nelem1-- != 0)); do   ## loop nelem1 times
    array1 =("$1")              ## add arg to array1
    shift                       ## skip to next arg
  done
  
  nelem2=$1                     ## set no. elements in array 2
  
  shift                         ## ditto for array 2
  while ((nelem2-- != 0)); do
    array2 =("$1")
    shift
  done
  
  declare -p array1             ## output array contents
  declare -p array2
}

a1=("My dog" "has fleas")
a2=("my cat" has none)

myfunc ${#a1[@]} "${a1[@]}" ${#a2[@]} "${a2[@]}"

Example Use/Output

$ bash scr/tmp/stack/function-multi-array.sh
declare -a array1=([0]="My dog" [1]="has fleas")
declare -a array2=([0]="my cat" [1]="has" [2]="none")
  • Related