Bash function with an array input and output

前端 未结 2 1580
情书的邮戳
情书的邮戳 2021-01-27 19:25

If I define an array in bash shell:

a=()
a+=(\"A\")
a+=(\"B\")
a+=(\"C\")

I can interact with it as expected:

echo \"${a[0]}\"
         


        
2条回答
  •  北海茫月
    2021-01-27 20:19

    bash does not have array values. The statement echo "${sorted[@]}" does not "return" an array value, it simply writes each element of the array to standard output, separated by a single space. (More specifically, the array expansion produces a sequence of words, one per element, that are then passed to echo as arguments.)

    It is somewhat difficult to simulate in bash. You have to create a global array parameter, something you couldn't do inside a function until bash 4.2. Working with said array was difficult until namerefs were introduced in bash 4.3.

    sort_array () {
        declare -n input=$1     # Local reference to input array
        declare -ga "$2"        # Create the output array
        declare -n output="$2"  # Local reference to output array
    
        # As a simple example, just reverse the array instead
        # of sorting it.
        n=${#input[@]}
        for((i=n-1; i>=0; i--)); do
            echo "*** ${input[i]}"
            output+=( "${input[i]}" )
        done
    }
    

    Now, you pass sort_array two arguments, the names of the input and output arrays, respectively.

    $ a=("foo 1" "bar 2" "baz 3")
    $ sort_array a b
    $ echo "${b[0]}"
    baz 3
    

提交回复
热议问题