Passing Arrays to Functions

Su Suriya Ravichandran Updated 06 Dec 2026
10 min read ·Lesson 104 of 205

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:

  1. add_item cart "olive oil" passes two strings: the name cart and the item.
  2. local -n list=$1 makes list a reference to the variable whose name is in $1, that is, to cart.
  3. list+=("$2") appends to cart through the reference. No copy is made.
  4. After the function returns, the reference list is gone, but the change to cart remains.

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.

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

NeedApproach
Read the values; the function must not change the caller's arrayexpand with "${arr[@]}"
Keep indexes of a sparse array or keys of an associative arrayname reference with local -n
Change the caller's arrayname reference
Pass two or more arraysname references (or lengths in front of each array)
Return an arrayfill a named array, or print lines and read them with mapfile
Support Bash older than 4.3expansion 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.

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Passing Arrays to Functions and get answers drawn from it.

Signed-in readers only.