Array Length
Array length is like counting how many eggs are actually in the carton. It tells you how many items your list holds right now.
In this page:
Syntax
${#array_name[@]}
Array Length
${#array[@]} gives the number of elements currently in the array. This works for both indexed and associative arrays. It's commonly used as the loop bound when iterating by numeric index instead of with foreach-style iteration.
Note:
${#array[@]}counts elements${#array[0]}(no@) instead gives the length of just the first element's string.
Example: Array Length
#!/bin/bash
items=("pen" "notebook" "eraser" "ruler")
echo "Number of items: ${#items[@]}"
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
Common Mistakes
- Using
${#arr}and getting the length of the first item, when the count is${#arr[@]}. - Expecting the length to be the highest index, when it is the number of items.
- Forgetting that unset indexes leave gaps, so the count is smaller than the last index plus one.
🔒
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: