Bash Passing An Array

Good grief so this should be easy. Passing an array as an argument to a function. Here is the sample code:

#/bin/bash

function foo {

  local p1=${1}
  local p2=(${2})
  local p3=${3}

  echo p1 is $p1
  echo p2 is $p2
  echo p3 is $p3

}

d1=data1
d2=data2
a=(bat bar baz)

foo "${d1}" "${a[@]}" "${d2}"

Obviously, it prints
data1
bat
bar

And what I want is:
data1
bat
data2

I would take
data1
bat bar baz
data2

As that would still be workable. I'm simply trying to stuff the array into the second argument somehow that isn't nasty and hard to understand. Obviously in the real example, there are multiple arrays being passed, so playing with the tokens isn't a great solution for me.

BASH is not a strongly typed language. You pass around strings and nothing but strings.

Converting an array to a string and back is easy though.

#!/bin/bash

arrpass () {
        local a2=( $2 ) # Split contents of $2 into array on IFS
        echo "${a2[1]}"
        echo "$1"
        echo "$2"
        echo "$3"
}

var1="asdf"
var2=( 1 2 3 4 )
var3="qwerty"

OLDIFS="$IFS"
IFS="|" # ${arr[*]} makes "1 2 3 4" if IFS=" ", "1|2|3|4" if IFS="|", etc
arrpas "$var1" "${var2[*]}" "${var3}"
IFS="$OLDIFS"
function foo {   
           local p1=${1};   
           local p2=(${2});   
           local p3=${3};    

           echo p1 is $p1;   
           echo p2 is $p2;   
           echo p3 is $p3;  
}

d1=data1
d2=data2
a=(bat bar baz)

foo "${d1}" "${a[*]}" "${d2}"
p1 is data1
p2 is bat
p3 is data2

--
Bye

1 Like