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 0