arrays - 传递给函数后在 bash 中获取数组长度时出错

标签 arrays bash shell

这种方法有什么问题我无法获得正确的数组长度值

#!/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/

相关文章:

c - C 中数组中的元素数量,不带 sizeof

javascript - 如何最有效地在 javascript 中仅包含两种类型的项目 0、1 的数组中查找项目的索引

bash - 如何处理 bash 脚本读取的 CSV 文件中的逗号

Bash 脚本 : Tar not working properly

c - 数组到变量

arrays - 在 Swift 中展平多个数组的所有值

bash - 使用 grep 和 cut delimiter 命令(在 bash shell 脚本 UNIX 中)- 和 "reversing"一样吗?

bash - 正则表达式读取的方式

c - 后台运行的程序的退出状态

linux - sh shell 中数组中的命令输出