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

前端 未结 4 490
醉梦人生
醉梦人生 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: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.

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-11-27 13:31

    You could pass the "scalar" value first. That would simplify things:

    f(){
      b=$1
      shift
      a=("$@")
    
      for i in "${a[@]}"
      do
        echo $i
      done
      ....
    }
    
    a=("jfaldsj jflajds" "LAST")
    b=NOEFLDJF
    
    f "$b" "${a[@]}"
    

    At this point, you might as well use the array-ish positional params directly

    f(){
      b=$1
      shift
    
      for i in "$@"   # or simply "for i; do"
      do
        echo $i
      done
      ....
    }
    
    f "$b" "${a[@]}"
    
    0 讨论(0)
  • 2020-11-27 13:33

    This will solve the issue of passing array to function:

    #!/bin/bash
    
    foo() {
        string=$1
        array=($@)
        echo "array is ${array[@]}"
        echo "array is ${array[1]}"
        return
    }
    array=( one two three )
    foo ${array[@]}
    colors=( red green blue )
    foo ${colors[@]}
    
    0 讨论(0)
提交回复
热议问题