23,120
社区成员
发帖
与我相关
我的任务
分享
testit ${myarray- }
这句话等同于
testit 1 2 3 4 5
看出问题来了吗,你传递的是多个参数,根本就不是一个数组啊!
如果在testit中还想把它还原成数组那就应该做么做:
local thistarray=($@)
原因是$@=1 2 3 4 5
;加一个括号就相当于数组了local thisarray=($*)
#!/bin/bash
function testit(){
local thisarray=($1)
echo "array length:"${#thisarray[@]}
sum=0
for (( i = 0; i < ${#thisarray- }; i++
- ))
do
echo "thisarray[$i]:"${thisarray[$i]}
sum="sum="$(($sum + ${thisarray[$i]}))
done
echo $sum
}
myarray=(1 2 3 4 5)
testit "${myarray
- }"
exit 0
array length:5
thisarray[0]:1
thisarray[1]:2
thisarray[2]:3
thisarray[3]:4
thisarray[4]:5
sum=15