Bash by Example: Arrays
Working with indexed arrays in Bash: declaration, assignment, and accessing elements with this sample code.
Code
#!/bin/bash
# Declare an indexed array
fruits=("Apple" "Banana" "Cherry")
# Access elements by index (0-based)
echo "First: ${fruits[0]}"
echo "Second: ${fruits[1]}"
# Add an element
fruits+=("Date")
# Print all elements (@)
echo "All: ${fruits[@]}"
# Print array length (#)
echo "Count: ${#fruits[@]}"
# Slicing an array
# Syntax: ${array[@]:offset:length}
echo "Slice: ${fruits[@]:1:2}"Explanation
Bash supports one-dimensional indexed arrays, which are zero-based lists of values. Unlike arrays in strongly typed languages, Bash arrays can hold elements of different types (strings, numbers) and are sparse, meaning indices do not need to be contiguous. You can initialize an array using parentheses (val1 val2 ...) or by assigning values to specific indices individually.
Working with arrays involves a specific syntax using curly braces. Without braces, Bash often interprets the variable name as just the first element. Key operations include:
- Accessing elements: Use
${array[index]}to get a specific value. - Expanding all elements: Use
${array[@]}to retrieve the entire list. - Getting length: Use
${#array[@]}to count the number of elements.
Arrays are particularly useful for managing lists of filenames, configuration options, or server names. They can be sliced using the :offset:length syntax, allowing you to extract subsets of data efficiently without external tools.
Code Breakdown
fruits=("...") initializes the array. Space is the delimiter between elements. If an element contains a space, it must be wrapped in quotes.${fruits[0]} accesses the first element. The curly braces {} are mandatory for array index expansion to avoid syntax errors.${fruits[@]} expands to all elements in the array. Using @ is generally preferred over * because it handles quoted strings correctly when iterating.${#fruits[@]} returns the length of the array (number of elements). The # prefix is the standard way to get length in Bash parameter expansion.
