0
0
Bash Scriptingscripting~10 mins

Accessing array elements in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
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.
Execution Sample
Bash Scripting
my_array=(apple banana cherry)
echo ${my_array[1]}
This script creates an array with three fruits and prints the second fruit.
Execution Table
StepActionArray StateIndex AccessedOutput
1Define array my_array[apple, banana, cherry]--
2Access element at index 1[apple, banana, cherry]1banana
3Print element[apple, banana, cherry]1banana
4End[apple, banana, cherry]--
💡 Script ends after printing the element at index 1.
Variable Tracker
VariableStartAfter 1Final
my_arrayundefined[apple, banana, cherry][apple, banana, cherry]
Key Moments - 2 Insights
Why does ${my_array[1]} print 'banana' and not 'apple'?
In bash arrays, indexing starts at 0. So index 0 is 'apple', index 1 is 'banana'. See execution_table row 2.
What happens if I try to access an index that does not exist?
Bash returns an empty string for out-of-range indexes. No error occurs. This is why we see no output if index is invalid.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 2?
Abanana
Bapple
Ccherry
DNo output
💡 Hint
Check the 'Output' column in execution_table row 2.
At which step is the array first defined?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Action' column for when the array is created.
If we change the index to 0 in ${my_array[0]}, what will be printed?
Abanana
Bapple
Ccherry
Dempty string
💡 Hint
Refer to variable_tracker for my_array contents and indexing starting at 0.
Concept Snapshot
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'.
Full Transcript
We start by defining an array named my_array with three elements: apple, banana, and cherry. Then we access the element at index 1, which is banana, because bash arrays start counting from zero. Finally, we print the accessed element. If an index is out of range, bash returns an empty string without error. This simple flow helps us get any item from an array by its position.