How to return an array in bash without using globals?

后端 未结 18 2016
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:58

    Use the technique developed by Matt McClure: http://notes-matthewlmcclure.blogspot.com/2009/12/return-array-from-bash-function-v-2.html

    Avoiding global variables means you can use the function in a pipe. Here is an example:

    #!/bin/bash
    
    makeJunk()
    {
       echo 'this is junk'
       echo '#more junk and "b@d" characters!'
       echo '!#$^%^&(*)_^&% ^$#@:"<>?/.,\\"'"'"
    }
    
    processJunk()
    {
        local -a arr=()    
        # read each input and add it to arr
        while read -r line
        do 
           arr+=('"'"$line"'" is junk') 
        done;
    
        # output the array as a string in the "declare" representation
        declare -p arr | sed -e 's/^declare -a [^=]*=//'
    }
    
    # processJunk returns the array in a flattened string ready for "declare"
    # Note that because of the pipe processJunk cannot return anything using
    # a global variable
    returned_string="$(makeJunk | processJunk)"
    
    # convert the returned string to an array named returned_array
    # declare correctly manages spaces and bad characters
    eval "declare -a returned_array=${returned_string}"
    
    for junk in "${returned_array[@]}"
    do
       echo "$junk"
    done
    

    Output is:

    "this is junk" is junk
    "#more junk and "b@d" characters!" is junk
    "!#$^%^&(*)_^&% ^$#@:"<>?/.,\\"'" is junk
    

提交回复
热议问题