Bash Array Reverse
Bash Array Reverse
In Bash scripting, reversing an array is useful for various tasks that require reversing the order of elements in an array.
Syntax
reversed_array=()
for (( i=${#array[@]}-1; i>=0; i-- )); do
reversed_array+=("${array[$i]}")
done
The basic syntax involves using a for
loop to iterate over the elements of the array in reverse order and store them in a new array.
Example Bash Array Reverse
Let's look at some examples of how to reverse an array in Bash:
1. Reverse an Array of Strings
This script initializes an array with string elements, reverses the array, and prints the reversed array.
#!/bin/bash
array=("element1" "element2" "element3")
reversed_array=()
for (( i=${#array[@]}-1; i>=0; i-- )); do
reversed_array+=("${array[$i]}")
done
echo "Reversed array: ${reversed_array[@]}"
In this script, the array variable array
is initialized with the elements 'element1', 'element2', and 'element3'. The for
loop iterates over the elements of the array in reverse order, and the elements are stored in the reversed_array
variable. The script then prints the reversed array.
2. Reverse an Array of Numbers
This script initializes an array with numeric elements, reverses the array, and prints the reversed array.
#!/bin/bash
array=(1 2 3)
reversed_array=()
for (( i=${#array[@]}-1; i>=0; i-- )); do
reversed_array+=("${array[$i]}")
done
echo "Reversed array: ${reversed_array[@]}"
In this script, the array variable array
is initialized with the elements 1, 2, and 3. The for
loop iterates over the elements of the array in reverse order, and the elements are stored in the reversed_array
variable. The script then prints the reversed array.
3. Reverse an Array with Elements from User Input
This script initializes an array with elements from user input, reverses the array, and prints the reversed array.
#!/bin/bash
array=()
while true; do
read -p "Enter an element (or 'done' to finish): " element
if [ "$element" == "done" ]; then
break
fi
array+=("$element")
done
reversed_array=()
for (( i=${#array[@]}-1; i>=0; i-- )); do
reversed_array+=("${array[$i]}")
done
echo "Reversed array: ${reversed_array[@]}"
In this script, the array variable array
is initialized as an empty array using ()
. The user is prompted to enter elements, which are added to the array using the +=
operator. When the user types 'done', the loop exits. The for
loop iterates over the elements of the array in reverse order, and the elements are stored in the reversed_array
variable. The script then prints the reversed array.
Conclusion
Reversing an array in Bash is a fundamental task for reversing the order of elements in an array in shell scripting. Understanding how to reverse arrays can help you manage and manipulate arrays effectively in your scripts.