Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass an array into a Bash function?

I have a Bash script that I can't figure out how to quote a variable in. Any help would be greatly appreciated.

This code works perfectly:

myfunction() {
    for i in "${BASE_ARRAY[@]}"
    do

I want to pass the name of my array as a variable to the function so I can reuse it with other arrays. This is the code I am trying that fails:

myfunction() {
    for i in "${$1[@]}"
    do

Then I pass the following to the function:

myfunction BASE_ARRAY
like image 524
steveH Avatar asked Oct 28 '25 17:10

steveH


1 Answers

I've never had success passing arrays into functions.

For me, the two options are always to pass content into a function, or (since bash 4.3) pass in an array name which will be accessed using a reference. Consider the following example.

#!/usr/bin/env bash

myfunc() {
        local -n arr=$1
        printf '%s\n' "${arr[1]}"
        arr[1]=HELLO
}

a=(one two three)

myfunc a
printf '%s\n' "${a[1]}"

which produces:

$ ./sample
two
HELLO

Note that local -n is like declare -n in that it doesn't provide a local copy of the array, but rather a local pointer to the original content. In this example, if you change $arr[], you are actually changing the original array, $a[].

The traditional method of passing array content to a function has been described so many times here on StackOverflow that it hardly bears mentioning; you'll have no difficulty finding examples.

like image 137
ghoti Avatar answered Oct 31 '25 08:10

ghoti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!