← Back to Bash Course | Chapter 6: Arrays | Lesson 6 of 10

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:

  1. Array Length
Syntax
bash
${#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

bash
#!/bin/bash
items=("pen" "notebook" "eraser" "ruler")
echo "Number of items: ${#items[@]}"
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
  1. Using ${#arr} and getting the length of the first item, when the count is ${#arr[@]}.
  2. Expecting the length to be the highest index, when it is the number of items.
  3. Forgetting that unset indexes leave gaps, so the count is smaller than the last index plus one.

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.