How to return array from bash function

Viewed 4227

I want to return an array from the function on bash and use this array in another function. But I get a string, not an array, can you please help me about how can I return an array from bash function, I am new in bash scripting, thanks.

array(){
          local words=("a a" "b b" "c c")
           echo ${words[@]}
    }

    getWord(){
           words=$(array)
           for word in "${words[@]}"; do
                echo "$word"
            done
    }

    getWord

It returns string of a a b b c c but my expected result should be an array.

1 Answers

Actually, looking at your code, you don't need to return anything; the "words" variable is global and thus can be used in the whole script.

WORKAROUNDS:

EDIT:

#!/bin/bash

array(){
       local words=("a" "b" "c")
       echo "${words[@]}"
}

getWord(){
       local arr=( $(array) )
       for word in "${arr[@]}"; do
            echo "$word"
        done
}

getWord

EDIT2:

#!/bin/bash

orig_IFS="$IFS"
array_IFS="," #Or whatever you want, mb a safer one

array(){
       IFS="${array_IFS}"
       local words=("a a" "b b" "c c")
       echo "${words[*]}"
       IFS="${orig_IFS}"
}

getWord(){
       IFS="${array_IFS}"
       arr=( $(array) )
       IFS="${orig_IFS}"
       for word in "${arr[@]}"; do
            echo "$word"
        done
}

getWord

EDIT3: as suggested per @Kamil Cuk

#!/bin/bash

array_IFS=$'\ca' #Maybe this is safer than using a single comma

array(){
       IFS="${array_IFS}" local words=("a a" "b b" "c c")
       echo "${words[*]}"
}

getWord(){
       IFS="${array_IFS}" arr=( $(array) )
       for word in ${arr[@]}; do #we don't need double quotes anymore
            echo "$word"
        done
}

getWord

Note the slight differences.

Related