How to pass array as an argument to a function in Bash

前端 未结 4 519
醉梦人生
醉梦人生 2020-11-27 12:55

As we know, in bash programming the way to pass arguments is $1, ..., $N. However, I found it not easy to pass an array as an argument to a functio

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 13:25

    You cannot pass an array, you can only pass its elements (i.e. the expanded array).

    #!/bin/bash
    function f() {
        a=("$@")
        ((last_idx=${#a[@]} - 1))
        b=${a[last_idx]}
        unset a[last_idx]
    
        for i in "${a[@]}" ; do
            echo "$i"
        done
        echo "b: $b"
    }
    
    x=("one two" "LAST")
    b='even more'
    
    f "${x[@]}" "$b"
    echo ===============
    f "${x[*]}" "$b"
    

    The other possibility would be to pass the array by name:

    #!/bin/bash
    function f() {
        name=$1[@]
        b=$2
        a=("${!name}")
    
        for i in "${a[@]}" ; do
            echo "$i"
        done
        echo "b: $b"
    }
    
    x=("one two" "LAST")
    b='even more'
    
    f x "$b"
    

提交回复
热议问题