How to return an array in bash without using globals?

后端 未结 18 2019
Happy的楠姐
Happy的楠姐 2020-11-29 21:36

I have a function that creates an array and I want to return the array to the caller:

create_array() {
  local my_list=(\"a\", \"b\", \"c\")
  echo \"${my_li         


        
18条回答
  •  一生所求
    2020-11-29 22:06

    This can also be done by simply passing array variable to the function and assign array values to this var then use this var outside of function. For example.

    create_array() {
      local  __resultArgArray=$1
      local my_list=("a" "b" "c")
      eval $__resultArgArray="("${my_list[@]}")"
    }
    
    my_algorithm() {
      create_array result
      echo "Total elements in the array: ${#result[@]}"
      for i in "${result[@]}"
      do
        echo $i
      done
    }
    
    my_algorithm
    

提交回复
热议问题