Introduction
Knowing the length of an array helps you understand how many items it holds. This is useful when you want to repeat actions for each item.
array=(item1 item2 item3)
length=${#array[@]}fruits=(apple banana cherry)
count=${#fruits[@]}
echo $countempty=()
echo ${#empty[@]}single=(onlyone)
echo ${#single[@]}numbers=(10 20 30 40 50) echo ${#numbers[@]}
#!/bin/bash # Define an array of colors colors=(red green blue yellow) # Print the array elements echo "Colors in the array: ${colors[@]}" # Get the length of the array length=${#colors[@]} # Print the length echo "Number of colors: $length"
my_array?${#array[@]} returns the count of elements in the array.${#array} returns the length of the first element, not the number of elements.files into a variable count?${#files[@]}.count=${#files[@]} stores the array length in count.arr=(apple banana cherry)
echo ${#arr[@]}arr has 3 elements: apple, banana, cherry.${#arr[@]} returns the number of elements, which is 3.data:data=(1 2 3 4)
echo ${#data}${#data} returns the length of the first element (string length), not the number of elements.${#data[@]} to get the count of elements in the array.items that may be empty or have elements. You want to print "Empty" if it has zero elements, or "Count: N" where N is the number of elements. Which script snippet correctly does this?${#items[@]} to get the number of elements. If zero, array is empty.${#items[@]} to print the count of elements, not ${#items} which is length of first element.Pass the test and this pattern moves unknown