Bash Script to Count Elements in Array
In Bash, you can count elements in an array using
${#array[@]}, for example: echo ${#my_array[@]} prints the number of elements.Examples
Inputmy_array=(apple banana cherry)
Output3
Inputmy_array=()
Output0
Inputmy_array=(one)
Output1
How to Think About It
To count elements in a Bash array, you think about how Bash stores arrays and how to access their size. Bash provides a special syntax
${#array[@]} that returns the number of elements. So, you just need to use this syntax with your array variable to get the count.Algorithm
1
Define or get the array variable.2
Use the syntax ${#array[@]} to get the count of elements.3
Print or return the count.Code
bash
#!/bin/bash
my_array=(apple banana cherry)
echo "Number of elements: ${#my_array[@]}"Output
Number of elements: 3
Dry Run
Let's trace counting elements in the array (apple banana cherry).
1
Define array
my_array=(apple banana cherry)
2
Count elements
Count = ${#my_array[@]} = 3
3
Print count
Output: Number of elements: 3
| Step | Action | Value |
|---|---|---|
| 1 | Define array | my_array=(apple banana cherry) |
| 2 | Count elements | 3 |
| 3 | Print output | Number of elements: 3 |
Why This Works
Step 1: Array length syntax
The ${#array[@]} syntax returns the number of elements in the array.
Step 2: Accessing array variable
You use the array name inside the braces to get its length.
Step 3: Printing the count
Using echo prints the count to the terminal.
Alternative Approaches
Using ${#array[*]} syntax
bash
#!/bin/bash
my_array=(apple banana cherry)
echo "Count: ${#my_array[*]}"This works the same as ${#array[@]} for counting elements but treats the array as a single word when quoted.
Using a loop to count elements
bash
#!/bin/bash my_array=(apple banana cherry) count=0 for element in "${my_array[@]}"; do ((count++)) done echo "Count: $count"
This manually counts elements by looping, less efficient but useful if you want to process elements while counting.
Complexity: O(1) time, O(1) space
Time Complexity
Counting elements with ${#array[@]} is constant time because Bash stores the array size internally.
Space Complexity
No extra memory is needed beyond the array itself; the operation is in-place.
Which Approach is Fastest?
Using ${#array[@]} or ${#array[*]} is fastest and simplest; looping to count is slower and unnecessary.
| Approach | Time | Space | Best For |
|---|---|---|---|
| ${#array[@]} | O(1) | O(1) | Quick count of array elements |
| ${#array[*]} | O(1) | O(1) | Same as above, watch quoting behavior |
| Loop counting | O(n) | O(1) | Counting with processing each element |
Use
${#array[@]} to quickly get the number of elements in any Bash array.Using
${#array} instead of ${#array[@]} returns the length of the first element, not the count of elements.