Concept Flow - Array length
Define array
Use length syntax
Shell calculates length
Output length
The shell script defines an array, then uses special syntax to get its length, which is printed as output.
my_array=(apple banana cherry)
echo ${#my_array[@]}| Step | Action | Variable/Expression | Value/Result | Output |
|---|---|---|---|---|
| 1 | Define array | my_array | (apple banana cherry) | |
| 2 | Evaluate length expression | ${#my_array[@]} | 3 | |
| 3 | Print length | echo ${#my_array[@]} | 3 | 3 |
| Variable | Start | After Step 1 | After Step 2 | Final |
|---|---|---|---|---|
| my_array | undefined | (apple banana cherry) | (apple banana cherry) | (apple banana cherry) |
| ${#my_array[@]} | undefined | undefined | 3 | 3 |
Array length in bash:
- Define array: my_array=(item1 item2 ...)
- Get length: ${#my_array[@]}
- Prints number of elements
- Use [@] to count all elements
- Empty array length is 0my_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