How to return an array in bash without using globals?

后端 未结 18 2057
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 21:57

    You can try this

    my_algorithm() {
      create_array list
      for element in "${list[@]}"
      do
        echo "${element}"
      done
    }
    
    create_array() {
      local my_list=("1st one" "2nd two" "3rd three")
    
      eval "${1}=()"
      for element in "${my_list[@]}"
      do
        eval "${1}+=(\"${element}\")"
      done
    }
    
    my_algorithm
    

    The output is

    1st one
    2nd two
    3rd three
    

提交回复
热议问题