向函数传递数组

向函数传递数组

Content #

向脚本函数传递数组变量的方法有点儿难以理解。将数组变量当作单个参数传递的话,它不会起作用:

$ cat badtest3
#!/bin/bash
# trying to pass an array variable

function testit {
   echo "The parameters are: $@"
   thisarray=$1
   echo "The received array is ${thisarray[*]}"
}

myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
testit $myarray
$
$ ./badtest3
The original array is: 1 2 3 4 5
The parameters are: 1
The received array is 1
$

如果试图将数组变量作为函数参数进行传递,则函数只会提取数组变量的第一个元素。

要解决这个问题,必须先将数组变量拆解成多个数组元素,然后将这些数组元素作为函数参数传递。最后在函数内部,将所有的参数重新组合成一个新的数组变量。来看下面的例子:

$ cat test10 #!/bin/bash

function testit { local newarray newarray=(`echo “$@”`) echo “The new array value is: ${newarray[*]}” }

myarray=(1 2 3 4 5) echo “The original array is ${myarray[*]}” testit ${myarray[*]} $ $ ./test10 The original array is 1 2 3 4 5 The new array value is: 1 2 3 4 5 $ #+end_src 该脚本用$myarray变量保存所有的数组元素,然后将其作为参数传递给函数。

From #

Linux命令行与shell脚本编程大全

数组变量(Bash)