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

codeforester
  • 39,467
  • 16
  • 112
  • 140
Fab
  • 1,145
  • 7
  • 20
  • 40
  • Why can't you just maintain a variable in global context, returning arrays is not the best of ways to design your code – Inian Apr 26 '17 at 11:32
  • If you can let us know your requirement, there are sure better ways to do this – Inian Apr 26 '17 at 11:33
  • Use a real programming language. – choroba Apr 26 '17 at 11:35
  • Technically, you can't even return a *single* array; you can *output* the *elements* of one or more arrays. – chepner Apr 26 '17 at 11:39
  • Try setting `my_list=("a b" "c d" "e f")` inside `create` and see what happens. – chepner Apr 26 '17 at 11:49
  • @Inian. I'm newbie. Could you provide me an example? – Fab Apr 26 '17 at 11:49
  • @Inian I have a file to read. Each line has two values and I want to store the first value of each line in the first array, the second value of each line in the second array. I want to do this with a function. – Fab Apr 26 '17 at 11:51
  • @chepner And then, how can I assign them to 3 variables? – Fab Apr 26 '17 at 11:53
  • See [How to return an array in bash without using globals?](http://stackoverflow.com/q/10582763/4154375). – pjh Apr 26 '17 at 18:21

1 Answers1

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
chepner
  • 497,756
  • 71
  • 530
  • 681