简体   繁体   English

在bash中将数组作为函数参数传递时出错

[英]Error while passing array as function parameter in bash

This is the code I am dealing with: 这是我正在处理的代码:

function execute {
    task="$1"
    servername="$2"
    "$task" "${servername[@]}" 

}


function someOtherThing {

    val=$1
    echo "$val"

}


function makeNecessaryDirectory {

    arr=("$@")
    echo "${arr[@]}"

}


dem=(1 2 3 4 5)


execute someOtherThing 1
execute makeNecessaryDirectory "${dem[@]}"

Output: 输出:

1
1

Expected output: 预期产量:

1
1 2 3 4 5

How to achieve this? 如何实现呢? I found no error logically. 我发现逻辑上没有错误。

Side question : Side question

Is it safe to always receive 2nd parameter as an array inside execute so that it can deal with both of the dependent functions, or i should have an explicit check inside execute ? execute始终将第二个参数作为数组接收是否安全,以便它可以处理两个相关函数,或者我应该在execute进行显式检查?

As explained in my comment 如我的评论中所述

You are passing the array as individual args to execute and then only passing the first one the makeNecessaryDirectory , so $@ is just the single argument passed which is 1. 您将数组作为要execute单个args传递,然后仅将第一个传递给makeNecessaryDirectory ,因此$@只是传递的单个参数,即1。

I would do it this way, I have added comments to the parts i have changed. 我将以这种方式进行操作,在已更改的部分中添加了注释。 It is only minor changes but should hopefully work for you. 这只是微小的变化,但希望对您有用。

#!/bin/bash

function execute {
    task="$1"
    servername="$2"
    "$task" "$servername"
    #No longer pass array here just pass servername as the name of array

}


function someOtherThing {

    val=$1
    echo "$val"

}


function makeNecessaryDirectory {

    local arr=("${!1}") 
    #Indirect reference to the first arg passed to function which is now the
    #name of the array

    for i in "${arr[@]}";
       do
           echo "$i"
       done

}


dem=(1 2 3 4 5)


execute someOtherThing 1
execute makeNecessaryDirectory 'dem[@]' #Pass the array name instead of it's contents

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM