1

I wrote a function which returns an array:

create(){
   my_list=("a" "b" "c")
   echo "${my_list[@]}"
}

result=$(create)
for var in result
do
    echo $var
done

Now, I'd like to extend it in order to return multiple arrays. For example, I'd like to write something like that:

create(){
    my1=("1" "2")
    my2=("3","4")
    my3=("5","6")
     echo "${my1[@]} ${my3[@]} ${my3[@]}"
}

and I'd like to get each of the returned arrays:

 res1= ...
 res2= ...
 res3= ...

Anyone could suggest me a solution? Thanks

9
  • Why can't you just maintain a variable in global context, returning arrays is not the best of ways to design your code Commented Apr 26, 2017 at 11:32
  • If you can let us know your requirement, there are sure better ways to do this Commented Apr 26, 2017 at 11:33
  • Use a real programming language. Commented Apr 26, 2017 at 11:35
  • Technically, you can't even return a single array; you can output the elements of one or more arrays. Commented Apr 26, 2017 at 11:39
  • Try setting my_list=("a b" "c d" "e f") inside create and see what happens. Commented Apr 26, 2017 at 11:49

1 Answer 1

1

You need to read with a while loop.

while read -r val1 val2; do
    arr1+=("$val1")
    arr2+=("$val2")
done < file.txt

There is no such thing as an array value in bash; you cannot use arrays the way you are attempting in your question. Consider this result:

create(){
   my_list=("a 1" "b 2" "c 3")
   echo "${my_list[@]}"
}

result=$(create)
for var in $result
do
    echo $var
done

This produces

a
1
b
2
c
3

not

a 1
b 2
c 3
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.