How to return an array in bash without using globals?

后端 未结 18 2009
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:08

    I recently discovered a quirk in BASH in that a function has direct access to the variables declared in the functions higher in the call stack. I've only just started to contemplate how to exploit this feature (it promises both benefits and dangers), but one obvious application is a solution to the spirit of this problem.

    I would also prefer to get a return value rather than using a global variable when delegating the creation of an array. There are several reasons for my preference, among which are to avoid possibly disturbing an preexisting value and to avoid leaving a value that may be invalid when later accessed. While there are workarounds to these problems, the easiest is have the variable go out of scope when the code is finished with it.

    My solution ensures that the array is available when needed and discarded when the function returns, and leaves undisturbed a global variable with the same name.

    #!/bin/bash
    
    myarr=(global array elements)
    
    get_an_array()
    {
       myarr=( $( date +"%Y %m %d" ) )
    }
    
    request_array()
    {
       declare -a myarr
       get_an_array "myarr"
       echo "New contents of local variable myarr:"
       printf "%s\n" "${myarr[@]}"
    }
    
    echo "Original contents of global variable myarr:"
    printf "%s\n" "${myarr[@]}"
    echo
    
    request_array 
    
    echo
    echo "Confirm the global myarr was not touched:"
    printf "%s\n" "${myarr[@]}"
    

    Here is the output of this code:

    When function request_array calls get_an_array, get_an_array can directly set the myarr variable that is local to request_array. Since myarr is created with declare, it is local to request_array and thus goes out of scope when request_array returns.

    Although this solution does not literally return a value, I suggest that taken as a whole, it satisfies the promises of a true function return value.

提交回复
热议问题