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

As we know, in bash programming, the method of passing arguments is $1 , ..., $N However, I found that it is not easy to pass an array as an argument to a function that 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, the function f receives two arguments: the first is assigned x which is an array, the second - y .

f can be called in two ways. The first method uses "${a[@]}" as the first argument, and the result:

 jfaldsj jflajds 

The second method uses "${a[*]}" as the first argument, and the result:

 jfaldsj jflajds LAST 

None of the results match what you want. So, does anyone have any ideas on how to properly pass an array between functions?

+41
arrays bash shell
May 09 '13 at 12:20
source share
4 answers

You cannot pass an array, you can only pass its elements (i.e. an extended 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" 

Another possibility is to pass an 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' fx "$b" 
+64
May 09 '13 at 12:33
source share

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 basic 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 on the manual page.

+27
Oct 18 '14 at 18:18
source share

You can pass a β€œscalar” value first. This will simplify the situation:

 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 can also use the positional parameters of array-ish directly

 f(){ b=$1 shift for i in "$@" # or simply "for i; do" do echo $i done .... } f "$b" "${a[@]}" 
+6
May 9 '13 at 12:52
source share

This will solve the problem of passing an array to a 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
Oct 21 '13 at
source share



All Articles