100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Bash

Arrays in Bash

Learn how to create, index, and iterate indexed and associative arrays in Bash, and how to use them to write scripts that handle lists of data correctly.

Bash Scripting In DepthIntermediate10 min readJul 9, 2026
Analogies

Arrays in Bash

Bash supports two kinds of arrays: indexed arrays, where elements are accessed by a numeric index starting at 0, and associative arrays, where elements are accessed by an arbitrary string key. Arrays solve a real problem plain variables can't: holding a genuine list of values — filenames, hostnames, key-value configuration — without resorting to fragile string concatenation with delimiters. Associative arrays were introduced in Bash 4.0 (2009), so scripts targeting strict POSIX sh or very old Bash (like macOS's stock Bash 3.2) cannot rely on them, but indexed arrays have been available since Bash 2.0 and are safe almost everywhere Bash itself is.

🏏

Cricket analogy: An indexed array is like a Test batting order numbered 1 to 11, while an associative array is like a scorecard keyed by player name (Kohli, Root) instead of slot number; associative arrays only work on 'modern rules' Bash 4.0+, not on an old-school scoring sheet.

Indexed arrays: creating and accessing

An indexed array is created with arr=(one two three) or by assigning individual elements like arr[0]=one. Indices don't need to be contiguous — you can set arr[5]=x on an otherwise empty array, leaving a sparse array. Accessing a single element uses ${arr[i]}; accessing all elements uses ${arr[@]} (each element as a separate word, the form you almost always want) or ${arr[*]} (all elements joined into one string using IFS). ${#arr[@]} gives the number of elements, and ${!arr[@]} gives the list of indices in use, which matters for sparse arrays.

🏏

Cricket analogy: Building arr=(one two three) is like naming your top three batsmen at once, while arr[5]=x is like slotting a specialist bowler straight into batting position 6, leaving gaps; ${arr[@]} reads out each player separately while ${arr[*]} reads the whole XI as one joined string.

bash
servers=("web01" "web02" "db01")

echo "${servers[0]}"        # web01
echo "${servers[@]}"        # web01 web02 db01
echo "${#servers[@]}"       # 3 (element count)

# Append an element
servers+=("cache01")

# Iterate safely, quoting the expansion
for host in "${servers[@]}"; do
    ping -c1 -W1 "$host" &>/dev/null && echo "$host: up" || echo "$host: down"
done

# Slice: elements 1 through 2 (offset 1, length 2)
echo "${servers[@]:1:2}"    # web02 db01

# Remove an element by index
unset 'servers[1]'
echo "${servers[@]}"         # web01 db01 cache01 (index 1 gap remains)

Associative arrays

Associative arrays require an explicit declare -A name before use — Bash cannot infer that a bare name=() should be associative rather than indexed. Keys are arbitrary strings, making associative arrays ideal for configuration-style lookups: mapping hostnames to IP addresses, environment names to URLs, or option flags to their descriptions. Iteration order for associative arrays is unspecified, so if order matters, sort the keys explicitly before iterating.

🏏

Cricket analogy: declare -A is like explicitly declaring a squad list keyed by player name rather than batting slot; Bash won't guess you meant a name-keyed squad sheet, so mapping venues to pitch conditions needs that explicit declaration, and player-order iteration isn't guaranteed unless you sort names first.

bash
declare -A env_urls
env_urls[dev]="https://dev.example.com"
env_urls[staging]="https://staging.example.com"
env_urls[production]="https://example.com"

target="staging"
echo "Deploying to ${env_urls[$target]}"

# Iterate keys in sorted order for deterministic output
for env in $(printf '%s\n' "${!env_urls[@]}" | sort); do
    echo "$env -> ${env_urls[$env]}"
done

# Check if a key exists
if [[ -v env_urls[qa] ]]; then
    echo "qa is configured"
else
    echo "qa is not configured"
fi

declare -a explicitly declares an indexed array and declare -A an associative array; using plain declare (or no declare at all) on an assignment like name=(a b c) always creates an indexed array, even if you intended keys. This is a common source of confusion for developers coming from languages where {}-style literals imply a dictionary/map.

${arr[@]} and ${arr[*]} behave identically until you look closely at quoting: "${arr[@]}" expands to each element as a separate, correctly quoted word (safe for elements with spaces), while "${arr[*]}" joins all elements into a single string separated by the first character of IFS. Using ${arr[*]} (or worse, an unquoted ${arr[@]}) in a for loop over elements containing spaces will silently misbehave, splitting or merging elements incorrectly.

Common patterns: building arrays from command output

A frequent need is turning command output (like a list of files or lines) into an array. mapfile (also called readarray) reads lines from stdin directly into an indexed array, one element per line, and is the safest modern approach — far preferable to the older, riskier pattern of arr=($(command)), which is subject to word splitting and glob expansion on every element.

🏏

Cricket analogy: mapfile is like a scorer transcribing each ball-by-ball commentary line straight into a numbered log, one entry per delivery; the older arr=($(command)) approach is riskier, like copying scores by hand and accidentally splitting a two-word player name into separate entries.

bash
# Safe: read each line of output into an array
mapfile -t running_containers < <(docker ps --format '{{.Names}}')
echo "Found ${#running_containers[@]} running containers"

for c in "${running_containers[@]}"; do
    echo " - $c"
done

# Split a delimited string into an array
IFS=':' read -ra path_dirs <<< "$PATH"
for dir in "${path_dirs[@]}"; do
    echo "$dir"
done
  • Indexed arrays use numeric indices (arr=(a b c)); associative arrays need explicit declare -A and use string keys.
  • "${arr[@]}" (quoted, with @) expands each element as a separate word — the form to use in loops.
  • ${#arr[@]} returns the element count; ${!arr[@]} returns the list of indices/keys in use.
  • Associative arrays are Bash 4.0+ only, unavailable on older Bash (e.g. macOS's stock 3.2) or POSIX sh.
  • mapfile -t arr < <(command) is the safe modern idiom for turning command output into an array, avoiding word-splitting pitfalls.
  • Associative array iteration order is unspecified — sort "${!arr[@]}" explicitly if deterministic order matters.

Practice what you learned

Was this page helpful?

Topics covered

#Bash#LinuxShellScriptingStudyNotes#DevOps#ArraysInBash#Arrays#Indexed#Creating#Accessing#DataStructures#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse