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 function which receives more than one argument. Here is one example:
f(){ x=($1) y=$2 for i in "${x[@]}" do echo $i done .... } a=("jfaldsj jflajds" "LAST") b=NOEFLDJF f "${a[@]}" $b f "${a[*]}" $b
As described, function f
receives two arguments: the first is assigned to x
which is an array, the second to y
.
f
can be called in two ways. The first way use the "${a[@]}"
as the first argument, and the result is:
jfaldsj jflajds
The second way use the "${a[*]}"
as the first argument, and the result is:
jfaldsj jflajds LAST
Neither result is as I wished. So, is there anyone having any idea about how to pass array between functions correctly?
To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.
To pass any number of arguments to the bash function simply put them right after the function's name, separated by a space. It is a good practice to double-quote the arguments to avoid the misparsing of an argument with spaces in it. The passed parameters are $1 , $2 , $3 …
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"
You can pass an array by name reference to a function in bash (since version 4.3+), by setting the -n
attribute:
show_value () # array index { local -n myarray=$1 local idx=$2 echo "${myarray[$idx]}" }
This works for indexed arrays:
$ shadock=(ga bu zo meu) $ show_value shadock 2 zo
It also works for associative arrays:
$ declare -A days=([monday]=eggs [tuesday]=bread [sunday]=jam) $ show_value days sunday jam
See also nameref
or declare -n
in the man page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With