0

I've refer Passing arrays as parameters in bash, but it failed. Here is my test script(both bash 3.0)

The bash version

GNU bash, version 3.00.16(1)-release (sparc-sun-solaris2.10)
Copyright (C) 2004 Free Software Foundation, Inc.

The script t.sh

fn() {
 local i
 local v1="$1"
 local v2="$2"
 local v3="$3"
 echo "v1=$1"
 echo "v2=$2"
 echo "v3=$3"
 declare -a a1=("${!1}")
 declare -a a2=("${!2}")
 echo "a1:"
 for i in ${!a1[*]} ; do
  echo "  ${a1[$i]}"
 done

 echo "a2:"
 for i in ${!a2[*]} ; do
  echo "  ${a2[$i]}"
 done
}
caller() {
  local a=("a1 a2" "a3" "a4")
  local b=("b1" "b2" "b3" "b4")
  echo "method 1:"
  fn "${a[@]}" "${b[@]}" $1 $2 $3
  echo "method 2:"  # workable on bash 4.2.45
  fn a[@] b[@] $1 $2 $3
}
caller c

Output

method 1:
v1=(a1 a2 a3 a4)
v2=(b1 b2 b3 b4)
v3=c
a1:
a2:
method 2:
v1=a[@]
v2=b[@]
v3=c
t.sh: array assign: line 10: syntax error near unexpected token `('
t.sh: array assign: line 10: `(a1 a2 a3 a4)'

expected output

...
a1:
   a1 a2
   a3
   a4
a2:
   b1
   b2
   b3
   b4
Community
  • 1
  • 1
Daniel YC Lin
  • 15,050
  • 18
  • 63
  • 96
  • I don't get the output you show. I see `v1=a1 a2 v2=a3 v3=a4`. – choroba Sep 11 '14 at 08:29
  • are you sure your bash is version 3.0 – Daniel YC Lin Sep 11 '14 at 08:34
  • bash version 4.1.11(2) – choroba Sep 11 '14 at 08:36
  • @DanielYCLin: Perhaps updating your version of bash? I mean, bash v3 is *ancient*... (8 years since the last release, to be exact, and four since v4 was released.) We don't fix K&R C problems anymore, either. ;-) That being said, as you see from my original question, array passing is *still* dodgy, so I am not surprised old versions of bash balk at it. – DevSolar Sep 11 '14 at 08:39
  • I'm not admin, I haven't permission to upgrade system. So, I just want a work around method. – Daniel YC Lin Sep 11 '14 at 08:46
  • @DanielYCLin: The linked question has some variations that are not quite as powerful as the accepted answer, but should work on older bash versions as well. – DevSolar Sep 15 '14 at 09:38
  • possible duplicate of [Passing arrays as parameters in bash](http://stackoverflow.com/questions/1063347/passing-arrays-as-parameters-in-bash) – DevSolar Sep 15 '14 at 09:39

1 Answers1

0

I'm not sure where you are having the issue, but I've confirmed operation on Bash 3.2.25:

./caller.sh
method 1:
v1=a1 a2
v2=a3
v3=a4
a1:

a2:

method 2:
v1=a[@]
v2=b[@]
v3=c
a1:
  a1 a2
  a3
  a4
a2:
  b1
  b2
  b3
  b4
03:36 lakehouse~/scr/tmp> bash --version
GNU bash, version 3.2.25(1)-release (i586-suse-linux-gnu)
Copyright (C) 2005 Free Software Foundation, Inc.
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85