bash how to pass array as an argument to a function -


as know, in bash programming way pass arguments is$1, ..., $n. however, found not easy pass array argument function receives more 1 argument. here 1 example:

f(){  x=($1)  y=$2   in "${x[@]}"    echo $i  done  .... }  a=(“jfaldsj jflajds" "last") b=noefldjf  f "${a[@]}" $b f "${a[*]}" $b 

as described, function freceives 2 arguments: first assigned x array, second y.

f can called in 2 ways. first way use "${a[@]}" first argument, , result is:

jfaldsj  jflajds 

the second way use "${a[*]}" first argument, , result is:

jfaldsj  jflajds  last 

neither result wished. so, there having idea how pass array between functions correctly.

you cannot pass array, can pass elements (i.e. expanded array).

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

the other possibility pass array name:

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

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -