shell_79.Linux数组变量和函数
数组变量和函数
向函数传递数组
向脚本函数传递数组变量的方法有点儿难以理解。将数组变量当作单个参数传递的话,它不
会起作用:
$ 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
# array variable to function test
function testit {local newarraynewarray=(`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
$
在函数内部,数组可以照常使用:
$ cat test11
#!/bin/bash
# adding values in an array
function addarray {local sum=0local newarraynewarray=(`echo "$@"`)for value in ${newarray[*]}dosum=$[ $sum + $value ]doneecho $sum
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=$(addarray $arg1)
echo "The result is $result"
$
$ ./test11
The original array is: 1 2 3 4 5
The result is 15
$
从函数返回数组
函数向 shell 脚本返回数组变量也采用类似的方法。
函数先用 echo 语句按正确顺序输出数组的各个元素,然后脚本再将数组元素重组成一个新的数组变量:
$ cat test12
#!/bin/bash
# returning an array value
function arraydblr { local origarray local newarray local elements local i origarray=($(echo "$@")) newarray=($(echo "$@")) elements=$[ $# - 1 ] for (( i = 0; i <= $elements; i++ )) { newarray[$i]=$[ ${origarray[$i]} * 2 ] } echo ${newarray[*]}
}
myarray=(1 2 3 4 5)
echo "The original array is: ${myarray[*]}"
arg1=$(echo ${myarray[*]})
result=($(arraydblr $arg1))
echo "The new array is: ${result[*]}"
$
$ ./test12
The original array is: 1 2 3 4 5
The new array is: 2 4 6 8 10