Introduction to Arrays
Creating an Indexed Array
You create an array literal by listing values inside parentheses separated by spaces, e.g. fruits=(apple banana cherry). Bash automatically assigns indices starting at 0, so apple is at index 0, banana at index 1, and so on.
Example: Creating an Indexed Array
#!/bin/bash
fruits=(apple banana cherry)
echo "First fruit: ${fruits[0]}"
echo "Second fruit: ${fruits[1]}"
Login to try C/C++/Java/PHP code in the editor
Accessing All Elements
${arr[@]} expands to every element of the array as separate words, which is what you want when looping over the contents. Using just $arr or ${arr} without an index only refers to element 0, a common beginner mistake.
Example: Accessing All Elements
#!/bin/bash
fruits=(apple banana cherry)
echo "All fruits: ${fruits[@]}"
echo "Just index 0 (via \$fruits): $fruits"
Login to try C/C++/Java/PHP code in the editor
Array Length
${#arr[@]} gives the total number of elements currently stored in the array, which is useful for loop bounds or validation. This is different from ${#arr} or ${#arr[0]}, which give the character length of the first element's string.
Example: Array Length
#!/bin/bash
fruits=(apple banana cherry)
echo "Number of fruits: ${#fruits[@]}"
echo "Length of first element string: ${#fruits[0]}"
Login to try C/C++/Java/PHP code in the editor
Appending to an Array
New elements can be added to the end of an array using the += operator with a parenthesized value list. This grows the array without needing to know its current length or rebuild it from scratch.
Warning: A full deep dive into arrays -- associative arrays, slicing, and more -- comes later in its own chapter.
Example: Appending to an Array
#!/bin/bash
fruits=(apple banana)
fruits+=(cherry)
fruits+=(date fig)
echo "Fruits now: ${fruits[@]}"
echo "Count: ${#fruits[@]}"
Login to try C/C++/Java/PHP code in the editor
- Forgetting the parentheses when creating an array literal;
fruits=apple bananadoes not create an array, it tries to runbananaas a command withfruits=appleas an environment prefix. - Using
$fruits(no index) and expecting all elements; that only gives you the first element (index 0) -- you need${fruits[@]}for the whole array. - Assuming array indices are always contiguous starting at 0 with no gaps; Bash indexed arrays are actually sparse, so removing an element leaves a gap rather than shifting later elements down.
- Create an indexed array with
arr=(one two three); indices start at 0 by default. - Access a single element with
${arr[0]}; access all elements with${arr[@]}. ${#arr[@]}gives the number of elements currently in the array.- Bash arrays are sparse -- unset elements leave gaps in the index sequence rather than being removed and renumbered.
Chapter Quiz — Complete all 13 topics to unlock
0/13 topics done
Complete these topics first: