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

前端 未结 4 522
醉梦人生
醉梦人生 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条回答
  •  旧时难觅i
    2020-11-27 13:15

    You can pass an array by reference to a function in bash 4.3+. This comes probably from ksh, but with a different syntax. The key idea is to set the -n attribute:

    show_value () # array index
    {
        local -n array=$1
        local idx=$2
        echo "${array[$idx]}"
    }
    

    This works for indexed arrays:

    $ shadock=(ga bu zo meu)
    $ show_value shadock 2
    zo
    

    It also works for associative arrays:

    $ days=([monday]=eggs [tuesday]=bread [sunday]=jam)
    $ show_value days sunday
    jam
    

    See also declare -n in the man page.

提交回复
热议问题