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

前端 未结 4 509
醉梦人生
醉梦人生 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: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[@]}"
    

提交回复
热议问题