打坏如何通过数组作为​​参数传递给函数 [英] bash how to pass array as an argument to a function

查看:136
本文介绍了打坏如何通过数组作为​​参数传递给函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我们所知,在bash编程来传递参数的方法是 $ 1 ... $ N 。然而,我发现它不容易传递一个数组作为参数传递给接收多个参数的函数。这里有一个例子:

As we know, in bash programming the way to pass arguments is$1, ..., $N. However, I found it not easy to pass an array as an argument to a function which receives more than one argument. Here is one example:

f(){
 x=($1)
 y=$2

 for i in "${x[@]}"
 do
  echo $i
 done
 ....
}

a=("jfaldsj jflajds" "LAST")
b=NOEFLDJF

f "${a[@]}" $b
f "${a[*]}" $b

如前所述,功能˚F接收两个参数:第一个被分配到X这是一个数组,第二到y

As described, function freceives two arguments: the first is assigned to x which is a array, the second to y.

˚F可以以两种方式调用。第一种方法使用$ {A [@]}作为第一个参数,其结果是:

f can be called in two ways. The first way use the "${a[@]}" as the first argument, and the result is:

jfaldsj 
jflajds

第二种方法使用$ {A [*]}作为第一个参数,其结果是:

The second way use the "${a[*]}" as the first argument, and the result is:

jfaldsj 
jflajds 
LAST

无论结果如我所愿。那么,有没有有关于如何正确传递函数之间阵列的任何想法的人。

Neither result is as I wished. So, is there anyone having any idea about how to pass array between functions correctly.

推荐答案

您不能传递一个数组,你只能通过它的元素(即扩展阵列)。

You cannot pass an array, you can only pass its elements (i.e. the expanded array).

#! /bin/bash
function f() {
    a=("$@")
    ((last_idx=${#a[@]} - 1))
    b=${a[last_idx]}
    unset a[last_idx]

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f "${x[@]}" "$b"
echo ===============
f "${x[*]}" "$b"

另一种可能性是通过名字来传递数组:

The other possibility would be to pass the array by name:

#! /bin/bash
function f() {
    name=$1[@]
    b=$2
    a=("${!name}")

    for i in "${a[@]}" ; do
        echo "$i"
    done
    echo "b: $b"
}

x=("one two" "LAST")
b='even more'

f x "$b"

这篇关于打坏如何通过数组作为​​参数传递给函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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