Array Length and Indices

Su Suriya Ravichandran Updated 06 Dec 2026
9 min read ·Lesson 101 of 205

Every Bash array has two separate pieces of information about its shape: how many elements it holds and which index numbers those elements sit at. In a freshly created array the two line up neatly (three elements at indexes 0, 1 and 2), but after elements are removed they drift apart. This lesson shows how to read both, how to tell them apart, and how to use them to answer everyday questions such as "is this array empty?", "what is the last element?" and "where is this value stored?".

Counting Elements with ${#arr[@]}

The number of elements in an array is written ${#arr[@]}. The # in front of a parameter name means "length of", and the [@] subscript applies it to the whole array instead of to one value:

fruits=(apple "dragon fruit" kiwi)
echo "count: ${#fruits[@]}"
echo "count star: ${#fruits[*]}"
count: 3
count star: 3

${#arr[*]} gives the same number. The difference between @ and * matters when the elements themselves are expanded (lesson 98), but not when they are counted, so most scripts simply use ${#arr[@]}.

The count includes only elements that exist. Elements holding an empty string do count, because they exist; indexes that were never assigned, or were removed with unset, do not.

Length of One Element: ${#arr[i]}

Putting an index in the brackets changes the meaning completely. ${#arr[i]} is the length of the string stored at index i, measured in characters:

echo "len of el 1: ${#fruits[1]}"
len of el 1: 12

dragon fruit has 12 characters, including the space. This is the same ${#var} string-length operator from lesson 54, applied to a single element. Numbers are strings too, so the length of an element holding 123 is 3:

n=(5 123 42)
echo "${#n[1]}"
3

The Missing Subscript Trap

Without any subscript, ${#fruits} does not count the array. A bare array name refers to element 0 (lesson 98), so ${#fruits} is the length of apple:

echo "no index: ${#fruits}"
no index: 5

A script that writes ${#arr} when it means the element count usually works by accident in testing (when element 0 happens to be short) and breaks later. The three forms side by side:

ExpressionMeaningResult for fruits
${#fruits[@]}number of elements3
${#fruits[1]}characters in element 112
${#fruits}characters in element 05

Listing the Indexes with ${!arr[@]}

An exclamation mark after the opening brace turns the expansion into a list of the indexes in use:

echo "indices: ${!fruits[@]}"
indices: 0 1 2

For a packed array this looks predictable, but the real value of ${!arr[@]} shows up in a sparse array, one with gaps between its indexes:

sp=([0]=a [3]=d [7]=h)
echo "count: ${#sp[@]}"
echo "indices: ${!sp[@]}"
count: 3
indices: 0 3 7

The array has three elements, but its highest index is 7. The count and the indexes answer different questions, and confusing them is the source of most index bugs.

As with values, quote the expansion when looping: for i in "${!sp[@]}". Indexes of an indexed array are always plain integers, so the quotes make no difference here, but the same loop over an associative array (lesson 103) has string keys that can contain spaces.

How Gaps Appear

Gaps come from explicit indexes in an assignment, as above, or from unset (lesson 99):

a=(a b c d e)
unset 'a[1]' 'a[3]'
echo "count ${#a[@]} indices ${!a[@]}"
count 3 indices 0 2 4

Bash does not move the remaining elements down. If a script needs the indexes to be 0 1 2 again, it can rebuild the array from its values, which renumbers it:

a=("${a[@]}")
echo "renumbered: ${!a[@]}"
renumbered: 0 1 2

Finding the Last Element and the Last Index

The Last Value

Since Bash 4.3, a negative index counts from the end of the array, so ${arr[-1]} is the last element whatever its index is:

echo "last value: ${sp[-1]}"
last value: h

The Last Index

The last index is the final item in the index list. Copying that list into its own array makes it easy to read:

idx=("${!sp[@]}")
echo "first index: ${idx[0]}"
echo "last index: ${idx[-1]}"
echo "next free: $(( ${idx[-1]} + 1 ))"
first index: 0
last index: 7
next free: 8

The "next free" index is where arr+=(value) would place a new element, since += appends after the highest index (lesson 99).

Why count - 1 Is Not the Last Index

In other languages the last position is the length minus one. That holds in Bash only for arrays without gaps:

echo "sp[count-1]: [${sp[${#sp[@]}-1]}]"
sp[count-1]: []

The count is 3, so the expression read index 2, which does not exist, and printed an empty string with no error. Use ${arr[-1]} for the last value and the index list for the last index.

Checking Whether an Array Is Empty

An array is empty when its count is zero. Arithmetic evaluation with (( )) (lesson 73) reads naturally:

e=()
echo "empty count: ${#e[@]}"
if (( ${#e[@]} == 0 )); then echo "e is empty"; fi
if [[ ${#fruits[@]} -gt 0 ]]; then echo "fruits has items"; fi
empty count: 0
e is empty
fruits has items

A variable that does not exist at all also reports a count of 0, so the same check covers "never created" and "created empty":

unset u
echo "unset count: ${#u[@]}"
unset count: 0

Reading ${e[-1]} from an empty array is an error, because there is no last element for the negative index to count back from:

bash: e: bad array subscript

Check the count first whenever an array might be empty.

Checking Whether an Index Exists

Testing the value with [[ -n ${arr[i]} ]] cannot tell a missing element from one that holds an empty string. The -v test (Bash 4.3 and later for array elements) checks whether the element is set, independent of its content. Quote the argument so the brackets are not treated as a glob pattern:

if [[ -v 'sp[3]' ]]; then echo "index 3 exists"; fi
if [[ ! -v 'sp[4]' ]]; then echo "index 4 missing"; fi
z=([0]="" [2]=x)
if [[ -v 'z[0]' ]]; then echo "z[0] exists though empty"; fi
index 3 exists
index 4 missing
z[0] exists though empty

The parameter expansion ${arr[i]+set} (lesson 45) gives the same answer and also works in older Bash versions. It expands to the word set when the element exists and to nothing otherwise:

echo "plus form: [${z[0]+set}] [${z[1]+set}]"
plus form: [set] []

Checking That an Index Is in Range

Before reading a position supplied by a user or computed by the script, a range check against the count gives a clear message instead of a silent empty value. For a packed array, the valid range is 0 to count minus 1:

nums=(10 20 30 40 50)
i=5
if (( i >= 0 && i < ${#nums[@]} )); then
    echo ok
else
    echo "index $i out of range (0-$(( ${#nums[@]} - 1 )))"
fi
index 5 out of range (0-4)

For a sparse array, use the -v test from the previous section instead, because a number inside the range might still be a gap.

Finding the Index of a Value

Bash has no built-in "index of" operation. The usual approach loops over the indexes and compares each element. Wrapped in a function, it prints the first matching index and uses its status to report success:

colors=(red green blue green)

find_index() {
    local target=$1; shift
    local -a list=("$@")
    local i
    for i in "${!list[@]}"; do
        if [[ ${list[i]} == "$target" ]]; then
            echo "$i"
            return 0
        fi
    done
    return 1
}

find_index green "${colors[@]}"
find_index purple "${colors[@]}" || echo "purple not found (status $?)"
1
purple not found (status 1)

How it works:

  1. The first argument is the value to look for; shift removes it so the remaining arguments are the array elements.
  2. local -a list=("$@") rebuilds them as a local array. Passing an array this way renumbers it from 0; lesson 104 covers how to pass the array itself when the original indexes matter.
  3. "$target" is quoted on the right side of == so it is compared as plain text, not as a pattern (lesson 70).
  4. return 0 after the first match stops the search; return 1 after the loop reports that nothing matched, which the caller tests with || or if.

To find every position of a value, drop the early return and print each match:

for i in "${!colors[@]}"; do
    [[ ${colors[i]} == green ]] && echo "  $i"
done
  1
  3

Using Lengths in Calculations

Element lengths and counts are ordinary integers, so they fit straight into arithmetic. Finding the longest word compares each element's length with the best one seen so far:

words=(cat elephant ox giraffe)
longest=""
for w in "${words[@]}"; do
    (( ${#w} > ${#longest} )) && longest=$w
done
echo "longest: $longest (${#longest})"
longest: elephant (8)

Adding up the lengths of all elements gives the total number of characters stored:

total=0
for f in "${fruits[@]}"; do (( total += ${#f} )); done
echo "chars: $total"
chars: 21

That is 5 for apple, 12 for dragon fruit and 4 for kiwi.

Counts in Slices

The count is also the natural way to describe slices relative to the end of an array (slices were introduced in lesson 98). A negative offset needs a space after the colon, so that Bash does not read :- as the default-value operator:

nums=(10 20 30 40 50)
echo "last two: ${nums[@]: -2}"
echo "all but last: ${nums[@]:0:${#nums[@]}-1}"
last two: 40 50
all but last: 10 20 30 40

The length part of the slice is evaluated as arithmetic, so ${#nums[@]}-1 can be written directly inside it without $(( )).

Choosing the Right Expression

QuestionExpression
How many elements are there?${#arr[@]}
How long is the string at index i?${#arr[i]}
Which indexes are in use?"${!arr[@]}"
What is the last value?${arr[-1]} (Bash 4.3+)
What is the last index?last item of "${!arr[@]}"
Is the array empty?(( ${#arr[@]} == 0 ))
Does index i exist?[[ -v 'arr[i]' ]] or ${arr[i]+set}

The next lesson moves from numeric indexes to associative arrays, where the index is an arbitrary string such as a host name or a user name, and the ${!arr[@]} expansion becomes the list of keys.

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 Array Length and Indices and get answers drawn from it.

Signed-in readers only.