【问题标题】:Pass multiple parameters to function, one being an array, another being a variable with spaces向函数传递多个参数,一个是数组,另一个是带空格的变量
【发布时间】:2022-01-18 22:17:10
【问题描述】:

我需要向 bash 中的函数发送多个参数。参数将是带空格的变量或数组

问题:

尝试在函数中调用我的输入参数数组时,我不断收到bad substitution。我也 bash 没有正确处理第一个参数,只显示到空格。 如何将这两种类型的参数传递给函数并在函数中正确使用?

这是我的代码:

#!/bin/bash

arr_conf=()

output(){
    echo $1
    for i in "${2[@]}";do
        echo $i
    done
}

arr_conf=(
"a=1"
"b=2"
"c=3"
)

name="Mr. Test"
output $name "${arr_conf[@]}"

这是输出:

$ ./test.sh
Mr.
./test.sh: line 7: ${$1[@]}: bad substitution

【问题讨论】:

    标签: arrays bash function parameters


    【解决方案1】:

    双引号变量。使用shift 从位置参数中删除第一个参数。

    #! /bin/bash
    output(){
        echo "$1"
    
        shift
        for i in "$@" ; do
            echo "$i"
        done
    }
    
    arr_conf=( "a=1" "b=2" "c=3" )
    name="Mr. Test"
    output "$name" "${arr_conf[@]}"
    

    【讨论】:

    • 啊!完美,知道这很简单。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2014-10-23
    • 2015-09-28
    • 2013-03-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多