How to return an array in bash without using globals?

后端 未结 18 2013
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:01

    Bash can't pass around data structures as return values. A return value must be a numeric exit status between 0-255. However, you can certainly use command or process substitution to pass commands to an eval statement if you're so inclined.

    This is rarely worth the trouble, IMHO. If you must pass data structures around in Bash, use a global variable--that's what they're for. If you don't want to do that for some reason, though, think in terms of positional parameters.

    Your example could easily be rewritten to use positional parameters instead of global variables:

    use_array () {
        for idx in "$@"; do
            echo "$idx"
        done
    }
    
    create_array () {
        local array=("a" "b" "c")
        use_array "${array[@]}"
    }
    

    This all creates a certain amount of unnecessary complexity, though. Bash functions generally work best when you treat them more like procedures with side effects, and call them in sequence.

    # Gather values and store them in FOO.
    get_values_for_array () { :; }
    
    # Do something with the values in FOO.
    process_global_array_variable () { :; }
    
    # Call your functions.
    get_values_for_array
    process_global_array_variable
    

    If all you're worried about is polluting your global namespace, you can also use the unset builtin to remove a global variable after you're done with it. Using your original example, let my_list be global (by removing the local keyword) and add unset my_list to the end of my_algorithm to clean up after yourself.

提交回复
热议问题