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

Array Length

In this page:

  1. Array Length

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[@]}"

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.