Search code examples
arraysbashfunctionreturnspace

Trouble displaying nth element of an array through function


I'm looking for retrieving the nth element from an array which contains spaces. Let's take for example:

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

I've created the following function:

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

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

The function may appear useless, but I need it to work like so. It was designed to return the $1th index of the given array.

I made some research on Internet and didn't found any answers. I know that the code I wrote (especially result="${@[$1]}") is false because

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

Unfortunately result="${$1} doesn't work and tried almost all combinaisons I could think of >.<" Does someone have any clues ?

Regards,


Solution

  • I have corrected your code. You need to have in mind that actually all the parameters you send to your function are an array of values.

    #!/bin/bash
    
    
    ARRAY=("This is" "a test" "array")
    
    function ReturnElementFromId() {
        local ix="$1" && shift
        local arr=("$@")
    
        echo "${arr[$ix]}"
    }
    
    echo `ReturnElementFromId 0 "${ARRAY[@]}"`
    

    Hope it helps!