在bash中将数组作为参数传递 [英] Passing arrays as parameters in bash

查看:32
本文介绍了在bash中将数组作为参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将数组作为参数传递给 bash 函数?

How can I pass an array as parameter to a bash function?

注意: 在 Stack Overflow 上没有找到答案后,我自己发布了我的粗略解决方案.它只允许传递一个数组,并且它是参数列表的最后一个元素.实际上,它根本不传递数组,而是传递其元素的列表,这些元素由 called_function() 重新组装成数组,但它对我有用.如果有人知道更好的方法,请随时在此处添加.

Note: After not finding an answer here on Stack Overflow, I posted my somewhat crude solution myself. It allows for only one array being passed, and it being the last element of the parameter list. Actually, it is not passing the array at all, but a list of its elements, which are re-assembled into an array by called_function(), but it worked for me. If someone knows a better way, feel free to add it here.

推荐答案

您可以使用如下方式传递多个数组作为参数:

You can pass multiple arrays as arguments using something like this:

takes_ary_as_arg()
{
    declare -a argAry1=("${!1}")
    echo "${argAry1[@]}"

    declare -a argAry2=("${!2}")
    echo "${argAry2[@]}"
}
try_with_local_arys()
{
    # array variables could have local scope
    local descTable=(
        "sli4-iread"
        "sli4-iwrite"
        "sli3-iread"
        "sli3-iwrite"
    )
    local optsTable=(
        "--msix  --iread"
        "--msix  --iwrite"
        "--msi   --iread"
        "--msi   --iwrite"
    )
    takes_ary_as_arg descTable[@] optsTable[@]
}
try_with_local_arys

会回显:

sli4-iread sli4-iwrite sli3-iread sli3-iwrite  
--msix  --iread --msix  --iwrite --msi   --iread --msi   --iwrite

编辑/注释:(来自下面的评论)

  • descTableoptsTable 作为名称传递并在函数中展开.因此,当作为参数给出时,不需要 $.
  • 请注意,即使使用 local 定义了 descTable 等,这仍然有效,因为局部变量对它们调用的函数是可见的.
  • ${!1} 中的 ! 扩展了 arg 1 变量.
  • declare -a 只是使索引数组显式,并不是绝对必要的.
  • descTable and optsTable are passed as names and are expanded in the function. Thus no $ is needed when given as parameters.
  • Note that this still works even with descTable etc being defined with local, because locals are visible to the functions they call.
  • The ! in ${!1} expands the arg 1 variable.
  • declare -a just makes the indexed array explicit, it is not strictly necessary.

这篇关于在bash中将数组作为参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆