Bash Script to Print Array Elements Easily
echo "${array[@]}" or loop through each element with for element in "${array[@]}"; do echo "$element"; done.Examples
How to Think About It
${array[@]}. Alternatively, you can loop through each element to print them one by one, which helps if you want each element on a new line or need to process them individually.Algorithm
Code
#!/bin/bash array=(apple banana cherry) # Print all elements in one line echo "${array[@]}" # Print each element on a new line for element in "${array[@]}"; do echo "$element" done
Dry Run
Let's trace printing the array (apple banana cherry) through the code
Define array
array=(apple banana cherry)
Print all elements at once
echo "${array[@]}" outputs: apple banana cherry
Loop through elements
for element in "${array[@]}"; do echo "$element"; done outputs: apple banana cherry
| Iteration | element | Output |
|---|---|---|
| 1 | apple | apple |
| 2 | banana | banana |
| 3 | cherry | cherry |
Why This Works
Step 1: Array Expansion
Using ${array[@]} expands all elements of the array, allowing you to access them together.
Step 2: Printing All Elements
Printing "${array[@]}" with echo shows all elements separated by spaces on one line.
Step 3: Looping Through Elements
The for loop iterates over each element, letting you print or process them individually.
Alternative Approaches
#!/bin/bash array=(apple banana cherry) for ((i=0; i<${#array[@]}; i++)); do echo "${array[i]}" done
#!/bin/bash array=(apple banana cherry) printf "%s\n" "${array[@]}"
Complexity: O(n) time, O(n) space
Time Complexity
Printing all elements requires visiting each element once, so time grows linearly with the number of elements.
Space Complexity
The array occupies space proportional to its size; printing does not require extra significant memory.
Which Approach is Fastest?
Using echo "${array[@]}" is fastest for printing all elements at once; looping is flexible but slightly slower.
| Approach | Time | Space | Best For |
|---|---|---|---|
| echo "${array[@]}" | O(n) | O(n) | Quick print all elements in one line |
| for loop over "${array[@]}" | O(n) | O(n) | Processing or printing elements individually |
| printf with "${array[@]}" | O(n) | O(n) | Printing each element on a new line efficiently |
"${array[@]}" to safely handle elements with spaces when printing or looping.${array[@]} can cause elements with spaces to split incorrectly.