Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

bash

shell

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 freceives 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?

like image 465
Red Lv Avatar asked May 09 '13 12:05

Red Lv


People also ask

How do you pass an array as a function argument?

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.

How do you pass an argument to a function in bash?

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 …


2 Answers

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" 
like image 96
choroba Avatar answered Sep 22 '22 09:09

choroba


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.

like image 42
Edouard Thiel Avatar answered Sep 26 '22 09:09

Edouard Thiel