无法通过函数显示数组的第 n 个元素

Trouble displaying nth element of an array through function

我要从包含空格的数组中检索第 n 个元素。 让我们举个例子:

ARRAY=("This is" "a test" "array")

我创建了以下函数:

ReturnElementFromId() {
    local result="${@[]}"
    echo result
}

echo `ReturnElementFromId 0 "${ARRAY[@]}"` 

该功能可能看起来毫无用处,但我需要它像这样工作。 它被设计为 return 给定数组的第 $1 个索引。

我在互联网上做了一些研究,但没有找到任何答案。 我知道我写的代码(尤其是 result="${@[]}")是错误的,因为

Victor Zamanian: @ (and *) are "Special Parameters" and because they are not valid array names, ${@} does refer to the numbered parameters

不幸的是 result="${} 不起作用,我尝试了几乎所有我能想到的组合 >.<" 有人有任何线索吗?

此致,

我已更正您的代码。您需要记住,实际上您发送给函数的所有参数都是一个值数组。

#!/bin/bash


ARRAY=("This is" "a test" "array")

function ReturnElementFromId() {
    local ix="" && shift
    local arr=("$@")

    echo "${arr[$ix]}"
}

echo `ReturnElementFromId 0 "${ARRAY[@]}"`

希望对您有所帮助!