Skip to content

Arrays

Creating Arrays

Arrays can be created explicitly, assigned from command output, or built using loops.

Explicit Declaration

fruits=(apple banana cherry)

Command Output Assignment

mapfile -t fruits < <(some-command)

Loop-Based Construction

while read line; do fruits+=($line); done < input.txt


Indexing and Accessing Elements

Elements are accessed via zero-based indices. Negative indices reference from the end (e.g., -1 is the last element), available in BASH 4.0+. Use ${#array[@]} to get the length.

Example: Accessing elements

echo "${fruits[0]}"        # Output: apple
echo "${fruits[-1]}"       # Output: cherry
echo "Array length: ${#fruits[@]}"  # Output: 3


Iterating Over Arrays

Arrays can be iterated by elements or indices.

Element-Based Iteration

for fruit in "${fruits[@]}"; do echo "$fruit"; done

Index-Based Iteration

for i in $(seq 0 $(( ${#fruits[@]} -1 ))); do echo "${fruits[$i]}"; done


Concatenation and Slicing

Arrays can be concatenated or sliced for subarray extraction.

Concatenation

combined=(${fruits[@]} ${vegetables[@]})

Slicing

echo "${fruits[@]:1:2}"   # Output: banana cherry


Key Takeaways

Array Creation Methods

Arrays can be created explicitly, via command output, or built with loops.

Indexing and Length

Use zero-based indexing, negative indices for reverse access (BASH 4.0+), and ${#array[@]} to get the length.

Iteration Techniques

Iterate by elements using for fruit in "${array[@]}" or by indices with seq and array indices.

Concatenation and Slicing

Concatenate arrays using += or array expansion, and slice with ${array[@]:start:length}.

Best Practices

Be cautious of word splitting and quoting when using command substitution to avoid unintended behavior.