Bash Script to Rotate Array Elements Easily
Use Bash array slicing like
rotated=("${arr[@]:1}" "${arr[0]}") to rotate an array by one position to the left.Examples
Inputarr=(1 2 3 4)
Outputrotated=(2 3 4 1)
Inputarr=(apple banana cherry)
Outputrotated=(banana cherry apple)
Inputarr=(single)
Outputrotated=(single)
How to Think About It
To rotate an array, think of moving the first element to the end and shifting all others left. You can do this by slicing the array from the second element to the end, then adding the first element at the end.
Algorithm
1
Get the original array.2
Extract all elements except the first one.3
Append the first element to the end of this extracted list.4
Combine them to form the rotated array.5
Return or print the rotated array.Code
bash
arr=(1 2 3 4) rotated=("${arr[@]:1}" "${arr[0]}") echo "${rotated[@]}"
Output
2 3 4 1
Dry Run
Let's trace rotating arr=(1 2 3 4) through the code
1
Original array
arr=(1 2 3 4)
2
Slice from second element
"${arr[@]:1}" expands to (2 3 4)
3
Append first element
"${arr[0]}" is 1, so rotated=(2 3 4 1)
| Step | rotated array |
|---|---|
| After slicing | 2 3 4 |
| After appending first element | 2 3 4 1 |
Why This Works
Step 1: Array slicing
Using ${arr[@]:1} extracts all elements from index 1 to the end, effectively skipping the first element.
Step 2: Appending first element
Adding ${arr[0]} at the end places the original first element last, completing the rotation.
Step 3: Combining results
The new array rotated holds the shifted elements, representing the rotated array.
Alternative Approaches
Using a loop to rotate
bash
arr=(1 2 3 4) rotated=() for ((i=1; i<${#arr[@]}; i++)); do rotated+=("${arr[i]}") done rotated+=("${arr[0]}") echo "${rotated[@]}"
This method uses a loop to build the rotated array, which is more verbose but clear for beginners.
Rotate right by one
bash
arr=(1 2 3 4) rotated=("${arr[-1]}" "${arr[@]:0:${#arr[@]}-1}") echo "${rotated[@]}"
This rotates the array to the right by one position, showing a different rotation direction.
Complexity: O(n) time, O(n) space
Time Complexity
The rotation requires copying all elements except one, so it runs in linear time relative to array size.
Space Complexity
A new array is created to hold the rotated elements, so space usage is linear in the number of elements.
Which Approach is Fastest?
Array slicing is fastest and simplest; loops add overhead but can be clearer for complex rotations.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Array slicing | O(n) | O(n) | Simple left rotation |
| Loop build | O(n) | O(n) | Clear step-by-step rotation |
| Right rotation slicing | O(n) | O(n) | Rotate right by one element |
Use Bash array slicing for simple and efficient rotation without loops.
Forgetting to quote array expansions can cause word splitting and unexpected results.