Arrays
Creating Arrays¶
Arrays can be created explicitly, assigned from command output, or built using loops.
Explicit Declaration
Command Output Assignment
Loop-Based Construction
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
Index-Based Iteration
Concatenation and Slicing¶
Arrays can be concatenated or sliced for subarray extraction.
Concatenation
Slicing
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.