Concept Flow - Accessing array elements
Define array
Access element by index
Print or use element
End
First, we create an array. Then we pick an element by its position number. Finally, we use or print that element.
my_array=(apple banana cherry)
echo ${my_array[1]}| Step | Action | Array State | Index Accessed | Output |
|---|---|---|---|---|
| 1 | Define array my_array | [apple, banana, cherry] | - | - |
| 2 | Access element at index 1 | [apple, banana, cherry] | 1 | banana |
| 3 | Print element | [apple, banana, cherry] | 1 | banana |
| 4 | End | [apple, banana, cherry] | - | - |
| Variable | Start | After 1 | Final |
|---|---|---|---|
| my_array | undefined | [apple, banana, cherry] | [apple, banana, cherry] |
Bash arrays start at index 0.
Use ${array[index]} to access elements.
Index must be a number.
Out-of-range index returns empty string.
Example: my_array=(a b c); echo ${my_array[1]} prints 'b'.