← Back to Bash Course | Chapter 6: Arrays | Lesson 1 of 10

Array Basics

An array is like an egg carton: one container with numbered slots, each holding its own item. You pick an item by saying which slot you want, starting at zero.

In this page:

  1. Array Basics
Syntax
bash
array_name=(value1 value2 value3)
echo "${array_name[0]}"

Array Basics

Bash arrays store multiple values in a single variable, declared with name=(value1 value2 value3). Individual elements are accessed with ${name[index]}, using zero-based indexing.

Arrays are one of the few compound data structures Bash offers natively.

Note: Always quote array expansions, like "${arr[@]}", to keep elements with spaces intact.

Example: Array Basics

bash
#!/bin/bash
fruits=("apple" "banana" "cherry")

echo "First fruit: ${fruits[0]}"
echo "Second fruit: ${fruits[1]}"
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Writing arr = (a b c) with spaces, which is a syntax error.
  2. Using $arr and expecting all items, when it gives only the first; use "${arr[@]}".
  3. Assuming arrays exist in plain sh, when they are a Bash feature.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.