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

艾哈努(Ahsanul Haque)

这是我正在处理的代码:

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[@]}"

输出:

1
1

预期产量:

1
1 2 3 4 5

如何实现呢?我发现逻辑上没有错误。

Side question

始终将第2个参数作为内部数组接收是否安全,execute以便它可以处理两个相关函数,还是我应该在内部进行显式检查execute

123

如我的评论中所述

您要将数组作为单个argsexecute传递,然后仅将第一个传递给makeNecessaryDirectory,因此$@传递的唯一参数也就是1。

我将以这种方式进行操作,在已更改的部分中添加了注释。这只是微小的更改,但希望可以为您工作。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

在C中将2维数组作为函数参数传递时出错

来自分类Dev

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

来自分类Dev

在C ++中将函数作为参数传递时出错

来自分类Dev

在C ++中将数组作为函数参数传递

来自分类Dev

在 PHP 中将数组作为函数的参数传递

来自分类Dev

在VBA中将命名范围作为参数传递时出错

来自分类Dev

在bash中将字符串作为函数的参数传递时,字符串被剪切

来自分类Dev

在bash中将字符串或数组作为参数传递

来自分类Dev

将 SKNode 作为函数参数传递时出错

来自分类Dev

在JavaScript中将数组作为内置函数参数传递

来自分类Dev

Rails-在模型函数中将数组作为参数传递

来自分类Dev

在bash中将“ *()”作为参数传递给程序

来自分类Dev

将ContainerInterface作为参数传递时出错

来自分类Dev

将“ const”作为“ this”参数传递时出错

来自分类Dev

在F#中将函数作为参数传递

来自分类Dev

在C中将函数作为参数传递的问题

来自分类Dev

在Swift中将函数作为参数传递

来自分类Dev

在Scala / Figaro中将函数作为参数传递

来自分类Dev

在C函数中将结构作为参数传递

来自分类Dev

在R中将if语句作为函数参数传递

来自分类Dev

在Netlogo中将函数作为参数传递

来自分类Dev

在C函数中将结构作为参数传递

来自分类Dev

在R中将if语句作为函数参数传递

来自分类Dev

在python函数中将列作为参数传递

来自分类Dev

在函数中将常量类作为参数传递

来自分类Dev

在 C++ 中将函数作为参数传递

来自分类Dev

在Powershell中将数组作为参数传递?

来自分类Dev

在TypeScript中将数组作为参数传递

来自分类Dev

在golang中将数组作为参数传递

Related 相关文章

热门标签

归档