0
0
Bash Scriptingscripting~5 mins

Array length in Bash Scripting - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Array length
Define array
Use length syntax
Shell calculates length
Output length
The shell script defines an array, then uses special syntax to get its length, which is printed as output.
Execution Sample
Bash Scripting
my_array=(apple banana cherry)
echo ${#my_array[@]}
This script defines an array with three fruits and prints the number of elements in it.
Execution Table
StepActionVariable/ExpressionValue/ResultOutput
1Define arraymy_array(apple banana cherry)
2Evaluate length expression${#my_array[@]}3
3Print lengthecho ${#my_array[@]}33
💡 All steps complete, array length 3 printed.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
my_arrayundefined(apple banana cherry)(apple banana cherry)(apple banana cherry)
${#my_array[@]}undefinedundefined33
Key Moments - 2 Insights
Why do we use ${#my_array[@]} instead of just ${#my_array}?
Using ${#my_array[@]} counts all elements in the array (see execution_table step 2). ${#my_array} would give the length of the first element string, not the array size.
What happens if the array is empty?
If the array is empty, ${#my_array[@]} evaluates to 0, meaning zero elements (not shown here but same syntax).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of ${#my_array[@]} at step 2?
A3
Bapple
Cundefined
D0
💡 Hint
Check the 'Value/Result' column in execution_table row for step 2.
At which step is the array actually printed to the screen?
AStep 1
BStep 3
CStep 2
DNo output is printed
💡 Hint
Look at the 'Output' column in execution_table to find when output appears.
If we add one more fruit to the array, how would the output change?
AOutput would stay 3
BOutput would be the new fruit name
COutput would be 4
DOutput would be empty
💡 Hint
Refer to variable_tracker and how length counts elements in the array.
Concept Snapshot
Array length in bash:
- Define array: my_array=(item1 item2 ...)
- Get length: ${#my_array[@]}
- Prints number of elements
- Use [@] to count all elements
- Empty array length is 0
Full Transcript
This example shows how to find the length of an array in bash scripting. First, an array named my_array is defined with three elements: apple, banana, and cherry. Then, the expression ${#my_array[@]} is used to get the number of elements in the array. The shell calculates this length as 3. Finally, the echo command prints the number 3 to the screen. It is important to use ${#my_array[@]} to count all elements, not just ${#my_array}, which would give the length of the first element string. If the array were empty, the length would be 0. This simple script helps count how many items are stored in a bash array.