这种方法有什么问题我无法获得正确的数组长度值
#!/bin/bash
foo(){
val=$@
len=${#val[@]}
echo "Array contains: " $val
echo "Array length is: " $len
}
var=(1 2 3)
foo ${var[@]}
输出:
Array contains: 1 2 3
Array length is: 1
最佳答案
将 val=$@
更改为 val=("${@}")
,您应该没问题。
This answer在 unix.stackexchange 中解释了原因:
You're flattening the input into a single value.
You should do
list=("${@}")
to maintain the array and the potential of whitespace in arguments.
If you miss out the " then something like
./script.sh "a b" 2 3 4
will return a length of 5 because the first argument will be split up
关于arrays - 传递给函数后在 bash 中获取数组长度时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49496810/