How to Reverse an Array in Bash? [8 Easy Methods]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

You can use the following methods to reverse an array in Bash:

  1. Using a for loop: for ((i=${#original_array[@]}-1; i>=0; i--)); do
    reversed_array+=("${original_array[i]}"); done
  2. Using while loop: while [ $length -gt 0 ]; do
    length=$((length-1))
    reversed_array+=("${original_array[$length]}"); done
  3. Using tac command: reversed_arr=( $(printf '%s\n' "${arr[@]}" | tac) )
  4. Using awk command: reversed_arr=($(echo "${array[@]}" | awk '{ for(i=NF;i>0;i--) print $i }'))
  5. Using rev command: reversed_arr=($(echo "${array[*]}" | rev))

A reversed array is a data structure in which the order of the original array is inverted. Reversing an array is a common yet essential operation in working with arrays in Bash. Learning about different techniques to reverse a Bash array effectively adds a new dimension to master data handling within arrays. This article will discuss 8 methods of how to reverse an array in Bash. It will mention loops and commands including several standard array accessing methods and functions within Bash scripts to reverse an array in Bash.

8 Methods to Reverse an Array in Bash

This section provides an in-depth analysis of 8 effective methods of how to reverse an array in Bash. It discusses reversing Bash arrays using for loop and while loop which are the most popular including being fast and efficient. Moreover, it mentions techniques like array slicing, and negative indexing to access array elements from the end to reverse the array. Furthermore, it will show use cases using commands like tac, awk, and rev and Bash functions to reverse an array in Bash.

1. Using the “for” Loop

The Bash for loop is a control flow statement that iterates over a given sequence to execute a given task throughout the sequence. This is a powerful tool to iterate over an array from the end to reverse the element order of the array using the condition for ((i=${#array[@]}-1; i>=0; i--)).

Here’s an example to reverse a Bash array using the for loop:

#!/bin/bash

# Original array
original_array=("one" "two" "three" "four" "five")
#print original_array
echo "original: ${original_array[@]}"

# Reversed array using loop
reversed_array=()
for ((i=${#original_array[@]}-1; i>=0; i--)); do
    reversed_array+=("${original_array[i]}")
done
echo
# Print the reversed array
echo "reversed: ${reversed_array[@]}"
EXPLANATION

In the above script, the expression original_array=("one" "two" "three" "four" "five") declares an array of 5 elements. Another array called reversed_array is also declared to store the array elements in the reverse sequential order. Then the loop for ((i=${#original_array[@]}-1; i>=0; i--)) iterates the original_array in the reverse order and appends each element in the reversed_array using the expression reversed_array+=("${original_array[i]}").

for loop to reverse bash array The original array (one two three four five) is reversed and printed in the reversed order (five four three two one) using the for loop.

2. Using the “while” Loop

The Bash while loop is also a handy tool to reverse an array in Bash by iterating the array elements from the reverse order like the following example:

#!/bin/bash

# Original array
original_array=("one" "two" "three" "four" "five")

# Reversed array using a while loop
reversed_array=()
i=${#original_array[@]}
while [ $i -gt 0 ]; do
    i=$((i-1))
    reversed_array+=("${original_array[$i]}")
done

# Print the reversed array
echo "${reversed_array[@]}"
EXPLANATION

In the above script, after initializing an array named original_array with 5 elements, the array length is stored in i variable and the while loop iterates over the array elements till the length becomes 0 using while [ $i -gt 0 ]. With each iteration, elements are appended to the reversed_array but in the reverse order which effectively reverses the original_array. Finally, the array is printed twice to display the difference after the reverse operation.

bash reverse array using while loop

3. Using Array Slicing

Array slicing is an essential concept in accessing a specific range of elements of an array. One common syntax is ${array_name[@ or *]:Start:Count} which accesses the number of items defined by Count starting from the index defined by Start. However, this can also reverse an array in  Bash. Here’s how:

#!/bin/bash

# Original array
original_array=(1 2 3 4 5)
#print array
echo "${original_array[@]}"

# Reversed array using array slicing
reversed_array=("${original_array[@]}")
reversed_array=("${reversed_array[@]: -1:1}" "${reversed_array[@]: -2:1}" "${reversed_array[@]: -3:1}" "${reversed_array[@]: -4:1}" "${reversed_array[@]: -5:1}")

# Print the reversed array
echo "${reversed_array[@]}"
EXPLANATION

In the above script,  after declaring the array named original_array, the array slicing code above takes each element from the reverse order and stores them in the new array variable reversed_array. Finally, the echo command prints the arrays to display the original array and the reversed array.

slicing to reverse bash array
Note: The above method is approachable when the array is not large. However, in terms of efficiency, loop-based methods are recommended.

4. Using Negative Index

One effective approach to accessing array elements from the last rather than from the beginning is to use a negative index. For example, the expression ${array[-1]} accesses the very last element of a Bash array. In addition, negative indices can be used to reverse an array. Here’s how:

#!/bin/bash

arr=(1 2 3)
echo "actual array: ${arr[@]}"
rev=(${arr[-1]} ${arr[-2]} ${arr[-3]})
echo "reversed array: ${rev[@]}"
EXPLANATION

In the above script, the expression rev=(${arr[-1]} ${arr[-2]} ${arr[-3]}) directly accesses each array item in the reverse order and stores them in a new array-type variable named rev. Finally, the command echo "reversed array: ${rev[@]} prints the elements after reversing the original array.

bash reverse array with negative indexAs you see the adoption of the negative index technique smartly reverses the Bash array.

5. Using the “tac” Command

The “tac” command is the reverse of the Linux cat command which usually displays the contents of a file in the reverse order. In the context of Bash arrays, the tac command takes input from the specified array and reverses its elements. Here’s an example:

#!/bin/bash

arr=(1 2 3 4 5)
echo "original array: ${arr[@]}"
# reversing the array with tac command
reversed_arr=( $(printf '%s\n' "${arr[@]}" | tac) )
echo
# print the reversed array 
echo "reversed array: ${reversed_arr[@]}"
EXPLANATION

In the above script, after declaring an array named arr using arr=(1 2 3 4 5), the expression reversed_arr=( $(printf '%s\n' "${arr[@]}" | tac) ) first prints the array elements, and this output is then piped into the tac command which reverses the elements of the array, and the final output is stored in the reversed_arr variable. Finally, the echo command verifies the reverse operation.

reversing elements using tac commandAs you can see from the terminal output the tac command effectively reverses a Bash array.

6. Using the “awk” Command

The awk command is a useful text-processing tool in Unix and Linux environments. This can also reverse the order of elements in an array-like structure. Here’s how:

#!/bin/bash
array=(1 2 3 4 5)
reversed=($(echo "${array[@]}" | awk '{ for(i=NF;i>0;i--) print $i }'))
echo "${reversed[@]}"
EXPLANATION

In the above script, after the declaration of array with 5 elements (1 2 3 4 5) using array=(1 2 3 4 5), the expression reversed=($(echo "${array[@]}" | awk '{ for(i=NF;i>0;i--) print $i }')) takes the array elements and pipes into the awk command that iterates over the specified fields ( NF is the number of fields) in the reverse order (array elements in this case) and stores them in the array-type variable reversed. The final command echo "${reversed[@]}" prints the elements to verify the reversing operation.

awk command reverses array itemsThe awk command reverses the original array order in Bash.

7. Using the “rev” Command

The rev command is used to reverse the order of characters in a line by either reading from a standard input or a file. So, this can help reverse a Bash array by passing it as the standard input but in the string format. Here’s an example:

#!/bin/bash 
array=(1 2 3 4 5)
string="${array[@]}"
reversed_string=$(echo "$string" | rev)
reversed=( $reversed_string )
echo "${reversed[@]}"
EXPLANATION

The above script creates an array using the expression array=(1 2 3 4 5) and then converts the array into a single string using  string="${array[@]}" and stores it in the variable named string. Then the expression reversed_string=$(echo "$string" | rev) takes the string and pipes it into the rev command that reverses the space-separated elements of the string. After that reversed=( $reversed_string ) converts the string into an array with the reverse order of elements which is finally seen after printing using the echo command.

element reverse using rev command

8. Using a Bash Function

It is possible to combine the necessary commands and expressions in the Bash function to reverse a Bash array and execute them by simply calling the function and passing the array as a parameter. Look at the example below to see a Bash function in action to reverse an array in Bash:

#!/bin/bash
reverse_array() {
    local array=("$@")
    local length=${#array[@]}
    local reversed=()

    for ((i = length - 1; i >= 0; i--)); do
        reversed+=("${array[i]}")
    done

    echo "${reversed[@]}"
}
# calling the function to reverse array:
array=(1 2 3 4 5)
echo "original: ${array[@]}"
reversed=$(reverse_array "${array[@]}")
echo "reversed: ${reversed[@]}"
EXPLANATION

In the above script, a function reverse_array is constructed using the basic expression reverse_array(). Inside the curly braces,{}, the expression local array=("$@") makes a local copy of the array and retrieves array length using local length=${#array[@]}. Then the loop for ((i = length - 1; i >= 0; i--)) iterates from the end and append each element to the array reversed in the reverse order. Finally, after calling the function by passing array=(1 2 3 4 5) as its parameter, it’s reversed successfully which is also evident after printing reversed array using echo "reversed: ${reversed[@]}".

Bash function to reverse arrayTerminal output to reverse an array in Bash using a function and passing the array as a parameter.

Conclusion

Reversing a Bash array is useful in terms of aiding algorithmic operations while opening creative possibilities for data representation. This article sheds light on 8 effective methods for how to reverse an array in Bash. It talks about for loop, while loop, and techniques like array slicing and negative index to reverse an array in Bash smartly. Furthermore, it mentions commands such as tac, rev, awk, and Bash functions to reverse a Bash array. Hope this article empowers the users and developers to hone this skill of reversing arrays in Bash enhancing scripting mastery.

People Also Ask

Can I reverse an associative array in Bash?

No, it is impossible to reverse an associative array in Bash since the associative arrays do not have any sequential order of storing and handling data. This is why it is impossible to reverse the order of an associative array seamlessly available for indexed arrays.

How do you print an array in reverse in Bash?

To print a Bash array in reverse, use the tac command with printf command within the syntax printf ‘%s\n’ “${array[@]}” | tac to print the array items in reverse order where the items will be printed in new lines each. For example, to print the array num=(1 2 3 4) in reverse, use the syntax printf '%s\n' "${num[@]}" | tac.

Output:

1

2

3

4

Is there any built-in function to reverse an array in Bash?

No. Bash doesn’t have any built-in function to reverse the order of an array.  However, you can use Bash for loop, while loop, etc., or external commands like tac and rev to reverse the array. For instance, to reverse an array num=(1 2 3), use the tac command within the syntax reversed_arr=( $(printf '%s\n' "${arr[@]}" | tac) )to reverse the array and store it in a new array variable called reversed_arr.

What is a reverse array in Bash?

A reverse array in Bash is an array where the order of its elements is inverted and presents the elements from the end to the beginning. The array reversing operation is commonly used for implementing algorithms, and creatively manipulating array data in Bash scripts.

Related Articles


<< Go Back to Array Operations in Bash | Bash Array | Bash Scripting Tutorial

Rate this post
Md Masrur Ul Alam

Assalamu Alaikum, I’m Md Masrur Ul Alam, currently working as a Linux OS Content Developer Executive at SOFTEKO. I completed my Bachelor's degree in Electronics and Communication Engineering (ECE)from Khulna University of Engineering & Technology (KUET). With an inquisitive mind, I have always had a keen eye for Science and Technolgy based research and education. I strongly hope this entity leverages the success of my effort in developing engaging yet seasoned content on Linux and contributing to the wealth of technical knowledge. Read Full Bio

Leave a Comment