6

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.

0

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

11 Comments

sorry I have revised the code the variable of words is local
Is there any good reason for that being that way?
actually, this code is just an example the main problem is how can I return an array from one function and use it in another function.
Using global variables. You can workaround the problem, though. See my edit.
The IFS="${array_IFS}" <newline> arr=( $(array) ) is written as a single line IFS="$array_IFS" arr=( $(array) ). That way you don't need to save IFS.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.