How to return an array in bash without using globals?

后端 未结 18 2040
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:54

    You were not so far out with your original solution. You had a couple of problems, you used a comma as a separator, and you failed to capture the returned items into a list, try this:

    my_algorithm() {
      local result=( $(create_array) )
    }
    
    create_array() {
      local my_list=("a" "b" "c")  
      echo "${my_list[@]}" 
    }
    

    Considering the comments about embedded spaces, a few tweaks using IFS can solve that:

    my_algorithm() {
      oldIFS="$IFS"
      IFS=','
      local result=( $(create_array) )
      IFS="$oldIFS"
      echo "Should be 'c d': ${result[1]}"
    }
    
    create_array() {
      IFS=','
      local my_list=("a b" "c d" "e f") 
      echo "${my_list[*]}" 
    }
    

提交回复
热议问题