Creating and Accessing Array Elements

Su Suriya Ravichandran Updated 06 Dec 2026
7 min read ·Lesson 98 of 205

An indexed array (lesson 97) can be filled in several ways: from a list written in the script, one element at a time, from the files that match a pattern, or from the output of a command. Once it exists, its elements are read with the ${name[index]} syntax, either one at a time, all together, or as a slice. This lesson covers each way of creating an array and each way of reading from it, and shows where quoting decides whether the result is correct.

Creating an Array from a List

The most common form is a compound assignment: the name, an equals sign, and a list of values in parentheses.

colors=(red green blue)
declare -p colors
declare -a colors=([0]="red" [1]="green" [2]="blue")

The values are separated by whitespace and numbered from 0 in the order they appear. As with any assignment, there must be no spaces around =.

Inside the parentheses, the normal rules of quoting apply. A value with a space needs quotes, and the list may be spread over several lines, with comments:

colors=(
    red      # primary
    "light green"
    blue
)
declare -p colors
declare -a colors=([0]="red" [1]="light green" [2]="blue")

Writing one element per line keeps long lists easy to read and makes changes in version control show up line by line.

Giving Indexes Explicitly

An element can be placed at a chosen index with [index]=value inside the list:

days=([1]=Mon [2]=Tue [7]=Sun)
declare -p days
declare -a days=([1]="Mon" [2]="Tue" [7]="Sun")

Explicit and automatic indexes can be mixed. A value without an index goes to the position after the previous one:

mix=(zero [4]=four five)
declare -p mix
declare -a mix=([0]="zero" [4]="four" [5]="five")

Assigning One Element at a Time

name[index]=value sets a single element. If the array does not exist yet, it is created:

arr[3]=x
declare -p arr
declare -a arr=([3]="x")

This form changes only the element named and leaves the rest of the array untouched, so it is also how you replace an existing value. Assigning a new compound list with name=(...), in contrast, replaces the whole array.

Creating an Array from Files

A glob pattern inside the parentheses expands to the matching file names (lesson 52), and each name becomes one element. Names with spaces are kept whole, because filename expansion happens after word splitting. In a folder containing a b.txt, c.txt and d.log:

txt=(*.txt)
declare -p txt
declare -a txt=([0]="a b.txt" [1]="c.txt")

When nothing matches, Bash leaves the pattern as it was, so the array gets one element containing the literal pattern. The nullglob option (lesson 149) makes a pattern with no match expand to nothing instead:

none=(*.pdf)
declare -p none
shopt -s nullglob
none=(*.pdf)
declare -p none
shopt -u nullglob
declare -a none=([0]="*.pdf")
declare -a none=()

With nullglob, an empty result can be detected by checking that the array has no elements (lesson 101).

Creating an Array from a String or Command Output

Writing an unquoted variable or command substitution inside the parentheses also creates an array, but it goes through word splitting and filename expansion. Both can produce surprises:

list="one two *.log"
words=($list)
declare -p words
declare -a words=([0]="one" [1]="two" [2]="app.log" [3]="d.log")

The *.log in the string was expanded into the names of matching files. The same applies to users=($(command)): it splits the output on spaces, tabs and newlines, so a line such as bo cara becomes two elements:

users=($(printf 'ana\nbo cara\n'))
declare -p users
declare -a users=([0]="ana" [1]="bo" [2]="cara")

Use this form only when you know the values contain no spaces and no glob characters. Bash has two builtins that split input in a controlled way instead.

Splitting a Line with read -a

read -a reads one line and stores its fields in an array. Setting IFS for the command chooses the separator:

IFS=, read -r -a parts <<< "id,name,,city"
declare -p parts
declare -a parts=([0]="id" [1]="name" [2]="" [3]="city")

The empty field between the two commas was kept as an empty element. No filename expansion happens, and the IFS=, setting applies only to this one read command. The -r option keeps backslashes as they are (lesson 31).

One Element per Line with mapfile

mapfile (also called readarray) reads input and stores each line as one element. The -t option removes the newline from the end of each line:

mapfile -t lines < app.log
declare -p lines
declare -a lines=([0]="Error code 7" [1]="ok" [2]="error code 9" [3]="warning")

Spaces inside a line are kept, and nothing is glob-expanded. To read the output of a command this way, use process substitution: mapfile -t lines < <(command) (lesson 151). A pipe such as command | mapfile -t lines does not work, because mapfile would run in a subshell and its array would be lost (lesson 61). mapfile needs Bash 4.0 or later.

Reading a Single Element

An element is read with ${name[index]}. The braces are required:

c=(red green blue yellow)
echo "${c[1]}"
green

Without braces, Bash reads $c (element 0) and then prints [1] as ordinary text:

echo "no braces: $c[1]"
no braces: red[1]

Arithmetic in the Index

The index of an indexed array is an arithmetic expression (lesson 49). A variable inside it can be written with or without $, and calculations are allowed:

i=2
echo "${c[i]} ${c[$i]} ${c[i+1]} ${c[i-2]}"
blue blue yellow red

This is why loops over indexes can write ${arr[i]} directly.

Negative Indexes

A negative index counts from the end of the array: -1 is the last element, -2 the one before it.

echo "last: ${c[-1]} second last: ${c[-2]}"
last: yellow second last: blue

Negative indexes need Bash 4.3 or later. On older versions, the last element is ${c[${#c[@]}-1]}, which only works when the array is not sparse. A negative index that reaches before the start of the array is an error:

echo "${c[-9]}"
echo "after"
bash: c: bad array subscript

after

The script continued after printing the error and an empty line.

Missing Elements

Reading an index that has no element gives an empty string, with no error and status 0:

echo "missing: [${c[10]}]"
missing: []

Under set -u (lesson 120), reading an unset element stops the script, just like reading an unset variable. The default-value forms of lesson 45 work on elements too: ${c[10]:-none} gives none.

Reading All Elements: @ and *

${name[@]} and ${name[*]} both refer to all elements. The difference appears when they are quoted, and it is the same difference as between "$@" and "$*" (lesson 43):

p=("a b" c)
printf '<%s>\n' "${p[@]}"
printf '<%s>\n' "${p[*]}"
printf '<%s>\n' ${p[@]}
<a b>
<c>
<a b c>
<a>
<b>
<c>
  • "${p[@]}" gives one word per element, exactly as stored. This is the form to use almost every time: in loops, as command arguments, and when copying an array (copy=("${p[@]}")).
  • "${p[*]}" joins all elements into one string, separated by the first character of IFS (a space by default).
  • Unquoted ${p[@]} or ${p[*]} are split again on whitespace and glob-expanded, so a b became two words. Unquoted forms lose the structure the array was created to protect.

Setting IFS changes the join character of "${p[*]}", which gives a quick way to join an array with a separator:

IFS=,; echo "${p[*]}"; unset IFS
a b,c

Remember to restore IFS afterward (here with unset IFS, which returns to the default behavior), or run the join in a subshell: (IFS=,; echo "${p[*]}").

Reading a Slice

${name[@]:start:count} gives count elements beginning at position start. Without count, it gives everything from start to the end. A negative start counts from the end and needs a space after the colon, so that Bash does not read :- as the default-value operator:

echo "slice: ${c[@]:1:2}"
echo "from 2: ${c[@]:2}"
echo "last two: ${c[@]: -2}"
printf '<%s>\n' "${c[@]:1:2}"
slice: green blue
from 2: blue yellow
last two: blue yellow
<green>
<blue>

Quoted, a slice gives one word per element, like "${c[@]}". Slices are the basis for removing the first element and for inserting elements in the middle (lesson 99).

Expansions on Elements

The parameter expansions of lesson 54 work on a single element and on all elements at once:

echo "${#c[3]}"
echo "${c[3]^^} ${c[0]/r/R} ${c[@]^}"
6
YELLOW Red Red Green Blue Yellow

${#c[3]} is the length of the string in element 3 (yellow has 6 characters), not the number of elements. ${c[3]^^} uppercases one element, ${c[0]/r/R} replaces text in one element, and ${c[@]^} capitalizes the first letter of every element. Applied with [@], each expansion works element by element, and the result can be stored as a new array: caps=("${c[@]^}"). The number of elements in an array is ${#c[@]}, covered with indexes in lesson 101.

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 Creating and Accessing Array Elements and get answers drawn from it.

Signed-in readers only.