Passing Arrays to Functions
Bash functions receive their input as positional parameters, $1, $2 and so on (lesson 89), and every positional parameter is a single string. There is no way to hand a whole array to a function as one argument. Instead, Bash offers two approaches: expanding the array into separate arguments, which gives the function a copy of the values, and passing the array's name, which lets the function work on the caller's array directly through a name reference. This lesson covers both, explains when to use each, and shows how a function can send an array back.
Why myfunc arr Does Not Pass the Array
Writing the array's name as an argument passes only that word. Writing $arr passes only element 0 (lesson 98):
show() { echo "got: [$1] count $#"; }
files=("a.txt" "my notes.txt" "c.txt")
show files
show $files
got: [files] count 1
got: [a.txt] count 1
Neither call gives the function the three file names. The function needs either the values themselves or a way to reach the array by its name.
Approach 1: Expanding the Array into Arguments
The quoted expansion "${arr[@]}" turns each element into one separate argument. Inside the function, "$@" holds them all:
print_all() {
local item
for item in "$@"; do
echo " [$item]"
done
echo " ($# items)"
}
print_all "${files[@]}"
[a.txt]
[my notes.txt]
[c.txt]
(3 items)
$# is the number of arguments, which here equals the number of elements. my notes.txt arrives intact because both sides are quoted: "${files[@]}" at the call, "$@" in the loop.
The two other spellings break the elements apart or glue them together, just as they do in loops (lesson 100):
print_all ${files[@]}
print_all "${files[*]}"
[a.txt]
[my]
[notes.txt]
[c.txt]
(4 items)
[a.txt my notes.txt c.txt]
(1 items)
Rebuilding a Local Array
Working with "$@" directly is fine for a simple loop. When the function needs array features such as indexes, slices or ${#arr[@]} under a clear name, it can rebuild the arguments into a local array:
sum() {
local -a nums=("$@")
local total=0 n
for n in "${nums[@]}"; do
(( total += n ))
done
echo "$total"
}
vals=(4 17 9)
echo "sum: $(sum "${vals[@]}")"
sum: 30
local -a nums=("$@") creates an indexed array that exists only while the function runs (lesson 92).
The Function Works on a Copy
Because the function received the values, not the array, changes inside it stay inside it:
double_copy() {
local -a c=("$@")
c[0]=changed
echo "inside: ${c[0]}"
}
double_copy "${vals[@]}"
echo "outside: ${vals[0]}"
inside: changed
outside: 4
This is often exactly what is wanted: the function cannot damage the caller's data by accident.
Indexes Are Not Passed
Arguments carry only values. A sparse array (lesson 101) arrives renumbered from 0, and the original positions are lost:
sp=([0]=a [5]=f)
idx() { local -a c=("$@"); declare -p c; }
idx "${sp[@]}"
declare -a c=([0]="a" [1]="f")
The same applies to associative arrays: "${map[@]}" passes the values without their keys. When indexes or keys matter, pass the name instead (Approach 2).
Combining Fixed Arguments with an Array
Ordinary arguments can come before the array. The function reads them first and uses shift (lesson 44) to remove them, leaving only the array elements in "$@":
log_each() {
local prefix=$1
shift
local f
for f in "$@"; do
echo "$prefix $f"
done
}
log_each "checking:" "${files[@]}"
checking: a.txt
checking: my notes.txt
checking: c.txt
Put the fixed arguments first. If the array came first, the function could not tell where it ends, because nothing marks the boundary between the last element and the next argument.
Passing Two Arrays by Value
That boundary problem is what makes passing two arrays awkward. One solution is to send each array's length in front of it, so the function knows how many arguments belong to each:
compare() {
local n1=$1; shift
local -a first=("${@:1:n1}")
shift "$n1"
local n2=$1; shift
local -a second=("${@:1:n2}")
echo "first: ${first[*]} (${#first[@]})"
echo "second: ${second[*]} (${#second[@]})"
}
a1=(x "y z")
a2=(1 2 3)
compare "${#a1[@]}" "${a1[@]}" "${#a2[@]}" "${a2[@]}"
first: x y z (2)
second: 1 2 3 (3)
"${@:1:n1}" is a slice of the positional parameters: n1 arguments starting at position 1. After copying them, shift "$n1" drops them, and the next argument is the second length. The output shows x y z because ${first[*]} joins the two elements x and y z with spaces, and the count confirms there are two. This works, but name references (below) are usually simpler for more than one array.
Approach 2: Passing the Array's Name with a Name Reference
A name reference, created with local -n (or declare -n), is a variable that acts as another name for a different variable. Every read or write through the reference goes to the variable it points to. Bash has supported name references since version 4.3.
The caller passes the array's name as a plain string, and the function binds a reference to it:
add_item() {
local -n list=$1
list+=("$2")
}
cart=(bread)
add_item cart "olive oil"
declare -p cart
declare -a cart=([0]="bread" [1]="olive oil")
How it works:
add_item cart "olive oil"passes two strings: the namecartand the item.local -n list=$1makeslista reference to the variable whose name is in$1, that is, tocart.list+=("$2")appends tocartthrough the reference. No copy is made.- After the function returns, the reference
listis gone, but the change tocartremains.
Because the function reaches the real array, it sees the real indexes too:
show_ref() {
local -n arr=$1
local i
for i in "${!arr[@]}"; do
echo " $i: ${arr[i]}"
done
}
show_ref sp
0: a
5: f
Compare this with the renumbered copy in the previous section.
Name References and Associative Arrays
A name reference works for associative arrays in the same way, keeping all keys:
print_map() {
local -n _pm=$1
local -a _pm_keys
local k
mapfile -t _pm_keys < <(printf '%s\n' "${!_pm[@]}" | sort)
for k in "${_pm_keys[@]}"; do
echo " $k=${_pm[$k]}"
done
}
declare -A cfg=([host]=example.com [port]=8080)
print_map cfg
host=example.com
port=8080
A function can also add or change keys in the caller's associative array. This one sets a key only when it is not already present:
set_default() {
local -n _sd=$1
[[ -v "_sd[$2]" ]] || _sd[$2]=$3
}
set_default cfg port 80
set_default cfg mode prod
print_map cfg
host=example.com
mode=prod
port=8080
port already existed, so it kept 8080; mode was new and was added.
Choosing Names That Do Not Clash
A name reference resolves the name it was given using Bash's normal lookup rules, which are dynamic (lesson 93): if the function has a local variable with the same name as the caller's array, the reference finds the local one first. This function has a local array called items, and the caller's array happens to be called items too:
grow2() {
local -n target=$1
local -a items=(x)
target+=("${items[@]}")
}
items=(a)
grow2 items
declare -p items
declare -a items=([0]="a")
The caller's array is unchanged. Inside the function, target pointed to the name items, which at that moment meant the local array, so the function appended to its own local copy and threw it away on return.
Passing the same name as the reference itself is another clash. With a function grow() { local -n ref=$1; ref+=(new); } and a caller's array named ref, the call grow ref makes Bash detect a reference to itself and print warnings:
bash: local: warning: ref: circular name reference
bash: warning: ref: circular name reference
bash: warning: ref: circular name reference
In Bash 5.2.21 the append still reached the caller's array after the warnings, but code that depends on this is fragile.
The usual protection is to give the reference and every local variable in such functions a prefix unlikely to appear in caller code, often built from the function name, as _pm and _sd above:
utils_grow() {
local -n _ug_list=$1
_ug_list+=(new)
}
list=(old)
utils_grow list
declare -p list
declare -a list=([0]="old" [1]="new")
Invalid Names
The name passed in must be a valid variable name. Anything else is rejected when the reference is created:
bash: local: `x y': invalid variable name for name reference
When the name comes from outside the script, check it before using it, or keep the decision inside the script so only known names are passed.
Returning an Array from a Function
return only carries a status from 0 to 255 (lesson 90), and command substitution captures one string (lesson 91). There are two common ways to give an array back to the caller.
Fill the Caller's Array by Name
The caller names the array that should receive the result, and the function writes into it through a reference:
split_csv() {
local -n _sc_out=$1
IFS=, read -r -a _sc_out <<< "$2"
}
split_csv parts "alpha,beta gamma,delta"
declare -p parts
declare -a parts=([0]="alpha" [1]="beta gamma" [2]="delta")
read -a stores the fields in the array behind _sc_out, which is parts. IFS=, applies only to that read command, so the comma is the separator and the space in beta gamma is kept. If parts did not exist before the call, it is created as a global variable.
Print One Element per Line and Read It Back
Without name references, the function prints the elements, one per line, and the caller collects them with mapfile from process substitution:
evens() {
local n
for n in "$@"; do
(( n % 2 == 0 )) && printf '%s\n' "$n"
done
return 0
}
mapfile -t ev < <(evens 1 2 3 4 10)
declare -p ev
declare -a ev=([0]="2" [1]="4" [2]="10")
The return 0 at the end matters: without it, the function's status would be the status of the last (( )) test, which is 1 when the last number is odd. The printing method keeps the function free of side effects and works in any Bash version with mapfile (4.0), but it cannot carry elements that contain newlines, and it runs the function in a subshell, so any other variables the function sets are lost.
Reading Global Arrays Without Arguments
Functions can also read and change a global array directly by its name, without any argument at all:
no_args() {
echo "sees: ${vals[*]}"
vals+=(99)
}
no_args
echo "after: ${vals[*]}"
sees: 4 17 9
after: 4 17 9 99
This is simple, but it ties the function to one particular array name, so it cannot be reused for another array, and a reader of the call no_args cannot see that it changes vals. Passing the name as an argument makes the dependency visible at every call.
Empty Arrays
An empty array expands to no arguments at all, so the function sees $# as 0, which is the same as calling it with nothing:
none=()
print_all "${none[@]}"
(0 items)
Functions that need at least one element should check $# (or ${#ref[@]} with a reference) and report an error.
Choosing an Approach
| Need | Approach |
|---|---|
| Read the values; the function must not change the caller's array | expand with "${arr[@]}" |
| Keep indexes of a sparse array or keys of an associative array | name reference with local -n |
| Change the caller's array | name reference |
| Pass two or more arrays | name references (or lengths in front of each array) |
| Return an array | fill a named array, or print lines and read them with mapfile |
| Support Bash older than 4.3 | expansion and printing only; name references are not available |
The final lesson of this section brings together the traps seen across the array lessons, from unquoted expansions to forgotten declarations, and shows how to recognize each one.