0
0
Bash Scriptingscripting~10 mins

Indexed array declaration in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Indexed array declaration
Start script
Declare indexed array
Assign values to array elements
Access or print array elements
End script
This flow shows how a bash script declares an indexed array, assigns values, and accesses them.
Execution Sample
Bash Scripting
fruits=("apple" "banana" "cherry")
echo ${fruits[0]}
echo ${fruits[1]}
echo ${fruits[2]}
Declare an indexed array named fruits with three elements and print each element.
Execution Table
StepActionArray StateOutput
1Declare array fruits with elements apple, banana, cherry["apple", "banana", "cherry"]
2Print fruits[0]["apple", "banana", "cherry"]apple
3Print fruits[1]["apple", "banana", "cherry"]banana
4Print fruits[2]["apple", "banana", "cherry"]cherry
5End of script["apple", "banana", "cherry"]
💡 All array elements accessed and printed, script ends.
Variable Tracker
VariableStartAfter DeclarationFinal
fruitsundefined["apple", "banana", "cherry"]["apple", "banana", "cherry"]
Key Moments - 2 Insights
Why do array indices start at 0 in bash?
Bash arrays are zero-indexed, so the first element is at index 0 as shown in execution_table steps 2-4.
What happens if I try to access an index that was not assigned?
Accessing an unassigned index returns an empty string, because only declared indices hold values, as seen in the array state in execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output at step 3?
Abanana
Bapple
Ccherry
Dundefined
💡 Hint
Check the Output column for step 3 in the execution_table.
At which step is the array fruits declared?
AStep 3
BStep 2
CStep 1
DStep 4
💡 Hint
Look at the Action column to find when the array is first created.
If you add a new element fruits[3]="date", what will be the array state after declaration?
A["apple", "banana", "cherry"]
B["apple", "banana", "cherry", "date"]
C["date"]
Dundefined
💡 Hint
Adding an element at index 3 appends it to the array, expanding its state.
Concept Snapshot
Indexed array declaration in bash:
fruits=("apple" "banana" "cherry")
Access elements by index: ${fruits[0]}
Indices start at 0
Unassigned indices return empty
Use parentheses to declare arrays
Full Transcript
This lesson shows how to declare an indexed array in bash scripting. The array named fruits is created with three elements: apple, banana, and cherry. Each element is accessed by its index starting at zero. The script prints each element in order. The array state remains the same throughout the script. Beginners often wonder why indices start at zero and what happens if an index is not assigned. The answer is that bash arrays are zero-indexed and unassigned indices return empty strings. Adding new elements expands the array. This visual trace helps understand how arrays work step-by-step.