Indexed Arrays in Bash

Su Suriya Ravichandran Updated 06 Dec 2026
6 min read ·Lesson 97 of 205

An indexed array is a variable that holds a list of values, each stored under a number called its index. Where an ordinary variable holds one string, an array holds many, and each one can be read, changed or removed on its own. Arrays are the tool Bash offers for any list whose items may contain spaces or special characters: file names, command-line options, lines of a file, or results collected in a loop.

Bash has two kinds of arrays. Indexed arrays, covered in this lesson and lessons 98 to 101, use whole numbers as indexes. Associative arrays (lessons 102 and 103) use strings as keys.

Why Arrays Exist

Before arrays, the usual way to keep a list in a shell script was a single string with the items separated by spaces. That breaks as soon as an item contains a space:

files="report one.txt notes.txt"
for f in $files; do echo "[$f]"; done
[report]
[one.txt]
[notes.txt]

The string has no memory of where one item ends and the next begins. The unquoted $files is split on every space (word splitting, lesson 53), so the file name report one.txt became two words. Quoting "$files" does not help either, because then the whole string is one item.

An array stores each item separately, so nothing has to be guessed:

files=("report one.txt" "notes.txt")
for f in "${files[@]}"; do echo "[$f]"; done
[report one.txt]
[notes.txt]

The quotes in the assignment decide where each item begins and ends, and the quoted expansion "${files[@]}" gives back exactly those items, one word per item, with spaces inside them kept.

How an Indexed Array Is Organized

Conceptually, an indexed array is a table of index and value pairs:

fruits=(apple banana cherry)
declare -p fruits
declare -a fruits=([0]="apple" [1]="banana" [2]="cherry")

declare -p (lesson 92) prints a variable together with its attributes. The -a flag marks an indexed array, and each element appears with its index in square brackets. A few properties follow from this:

  • Indexes start at 0. The first element is [0], the second [1], and so on.
  • Every value is a string. Bash has no separate number, boolean or nested-list types. A value such as 42 is stored as text and only treated as a number inside arithmetic (lesson 49).
  • Indexes do not have to be consecutive. An array may have elements at 0, 5 and 9 and nothing in between. Such an array is called sparse.
  • The size is not fixed. Elements can be added and removed at any time (lesson 99).

The Basic Operations

The syntax for working with arrays always uses braces. These are the operations you will use most, each covered in detail in the following lessons:

fruits=(apple banana cherry)
echo "first: ${fruits[0]}"
echo "third: ${fruits[2]}"
echo "all: ${fruits[@]}"
echo "count: ${#fruits[@]}"
echo "indices: ${!fruits[@]}"
first: apple
third: cherry
all: apple banana cherry
count: 3
indices: 0 1 2
ExpressionMeaningLesson
arr=(a b c)create an array from a list98
${arr[i]}the element at index i98
"${arr[@]}"all elements, each as a separate word98, 100
${#arr[@]}the number of elements101
${!arr[@]}the list of indexes that are in use100, 101
arr+=(d)append one or more elements99
unset 'arr[i]'remove one element99

The Array Name Alone Means Element 0

Using an array name without an index does not give the whole array. It gives element 0:

echo "plain \$fruits: $fruits"
plain $fruits: apple

This is a common surprise for beginners who expect $fruits to print the list. The reverse is also true: Bash treats every ordinary variable as if it were element 0 of an array, and assigning to another index turns it into an array:

name=Ana
echo "${name[0]} [${name[1]}]"
declare -p name
name[1]=Bo
declare -p name
Ana []
declare -- name="Ana"
declare -a name=([0]="Ana" [1]="Bo")

declare -- means a plain variable with no attributes. After name[1]=Bo, the same variable became an indexed array with the old value at index 0.

Sparse Arrays

Indexes can be given explicitly when the array is created. Elements that were never set simply do not exist:

nums=([0]=10 [5]=50 [9]=90)
declare -p nums
echo "count: ${#nums[@]} indices: ${!nums[@]}"
echo "nums[3]=[${nums[3]}]"
declare -a nums=([0]="10" [5]="50" [9]="90")
count: 3 indices: 0 5 9
nums[3]=[]

The array has three elements, not ten. Reading a missing index such as nums[3] gives an empty string without an error, just like reading an unset variable. Sparse arrays appear more often than you might expect, because removing an element with unset leaves a gap (lesson 99). This is why loops that walk an array by counting from 0 to the length can miss elements, and why looping over "${!arr[@]}" is safer (lesson 100).

Declaring an Array Explicitly

An array is created automatically by the first assignment, so a declaration is optional. declare -a makes the intent clear and creates an empty array:

declare -a empty
declare -p empty
echo "count ${#empty[@]}"
declare -a empty
count 0

Inside a function, local -a name creates a local array (lesson 92). Attributes can be combined with -a: for example declare -ai makes an array whose elements are evaluated as integers when they are assigned:

declare -ai scores=(10 20)
scores[2]="5 + 5"
declare -p scores
declare -ai scores=([0]="10" [1]="20" [2]="10")

Values of Any Kind

Because every element is a string, one array can hold numbers, words, empty strings and text with spaces side by side:

mixed=(42 "two words" 3.14 "")
echo "count ${#mixed[@]}"
printf '<%s>\n' "${mixed[@]}"
count 4
<42>
<two words>
<3.14>
<>

The empty string is a real element and is counted. printf repeats its format once for each argument, which makes it a convenient way to see exactly what an array contains.

A Practical Use: Building Command Arguments

One of the most valuable uses of arrays is collecting the arguments of a command. Storing options and a pattern in a plain string breaks on spaces, but an array keeps each argument whole. Given an app.log that contains Error code 7, ok, error code 9 and warning:

grep_opts=(-i -n)
pattern="error code"
grep "${grep_opts[@]}" "$pattern" app.log
1:Error code 7
3:error code 9

"${grep_opts[@]}" expanded to the two words -i and -n, and the pattern with its space stayed a single argument. A script can add options to such an array step by step, for example grep_opts+=(-w) when the user passes a flag, and run the command once at the end.

Limits of Bash Arrays

Arrays in Bash are simpler than lists in general-purpose languages, and a few limits are worth knowing from the start:

  • No nesting. An element cannot itself be an array. Lists of lists are usually handled with a separator inside each element, parallel arrays with the same indexes, or associative arrays with compound keys.
  • No export. Arrays cannot be passed to child processes through the environment:
fruits=(apple banana cherry)
export fruits
bash -c 'echo "child sees: [${fruits[0]}]"'
child sees: []
  • Passing to functions needs care. A function receives its arguments as a flat list, so arrays are passed by expanding them or by name (lesson 104).
  • Bash only. Arrays are not part of the POSIX shell standard. Dash, the sh of Debian and Ubuntu, rejects the syntax:
$ dash -c 'a=(1 2 3); echo ${a[0]}'
dash: 1: Syntax error: "(" unexpected

Scripts that use arrays need a Bash shebang (#!/usr/bin/env bash, lesson 26) and must be run with Bash, not sh script.sh.

Indexed arrays exist in every Bash version still in use, including Bash 3.2 on macOS, but some array features covered in the next lessons are newer. mapfile and associative arrays need Bash 4.0, and negative indexes such as ${arr[-1]} need Bash 4.3.

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 Indexed Arrays in Bash and get answers drawn from it.

Signed-in readers only.