Baeldung Pro – Linux – NPI EA (cat = Baeldung on Linux)
announcement - icon

Learn through the super-clean Baeldung Pro experience:

>> Membership and Baeldung Pro.

No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.

Partner – Orkes – NPI EA (tag=Kubernetes)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

1. Overview

Bash is one of the most commonly used command-line interpreters in Linux. One of the data structures in Bash is the array, which allows us to store a sequence of elements. When working with an array, it’s not uncommon to encounter a scenario that requires us to reverse the array.

In this tutorial, we’ll explore various ways to reverse a Bash array.

2. Reversing a Bash Array

In Bash, we can identify each element of an array with the help of its index. Thus, indices might come in handy when we’re reversing the array.

To demonstrate, we’ll use an array with the name numbers_array:

$ numbers_array=(1 2 3 4)

Now, let’s explore various ways to reverse this array. In addition, we’ll utilize the Bash script example.sh.

2.1. Manually Swapping Array Elements

In this approach, we’ll manually swap array elements in place so that we’re not required to create an additional array:

#!/bin/bash

# Initialize the original array
numbers_array=(1 2 3 4)

# Reverse the array in place
length=${#numbers_array[@]}
for (( i=0, j=length-1; i<j; i++, j-- )); do
    temp="${numbers_array[i]}"
    numbers_array[i]="${numbers_array[j]}"
    numbers_array[j]="$temp"
done

# Print the reversed array
echo "Reversed Array: ${numbers_array[@]}"

Let’s break down the command above:

  • for (( i=0, j=length-1; i<j; i++, j– )) – the for loop executes with the variables i representing the beginning of the array and j for the end of the array whereby it stops when i is no longer less than j
  • temp=”${numbers_array[i]}” – the temp variable temporarily stores the element at index i
  • numbers_array[i]=”${numbers_array[j]}” – updates the element at index i to the element at index j
  • numbers_array[j]=”$temp” – updates the element at index j to the original element at index i that’s stored in the temp variable

Now, let’s see the output of the Bash script example.sh:

$ bash example.sh
Reversed Array: 4 3 2 1

This approach exchanges elements in the array numbers_array from both ends toward the center.

2.2. Using the tac Command

Typically, the tac command helps to print files in reverse. In addition, we can use it to reverse the numbers_array array:

$ reversed_numbers=($(printf "%s\n" "${numbers_array[@]}" | tac))

Now, let’s explore the commands we use with command substitution ($()):

  • printf “%s\n” “${numbers_array[@]}” – prints each element of the numbers_array array on a new line
  • | tac – passes the output of the printf command as input to the tac command whereby tac reverses the order of the input items

Meanwhile, reversed_numbers=($(…)) captures the output of the command inside $() and stores it in the reversed_numbers array.

At this point, let’s display the contents of the reversed_numbers array:

$ echo "Reversed array: ${reversed_numbers[@]}"
Reversed array: 4 3 2 1

Here, we see that the array is reversed.

2.3. Using a for Loop

Here, we iterate over the original array numbers from the last to the first element and append each element to a new array.

So, let’s use a for loop to iterate over the original array in reverse order and add each element to the reversed_numbers array:

#!/bin/bash

# Initialize the original array
numbers_array=(1 2 3 4)

# Create a new array to hold the reversed elements
reversed_numbers=()

# Get the length of the array
length=${#numbers_array[@]}

# Inversely iterate through the array
for ((i=$length-1; i>=0; i--)); do
    reversed_numbers+=(${numbers_array[i]})
done

# Print the reversed array
echo ${reversed_numbers[@]}

Let’s discuss the command above:

  • length=${#numbers_array[@]} – evaluates the numbers of elements in the numbers_array array
  • for ((i=$length-1; i>=0; i–)) – the for loop iterates through the numbers_array starting from the last index ($length-1) to the first index (0)
  • reversed_numbers+=(${numbers_array[i]}) – appends each element of numbers_array to reversed_numbers in reverse order

Now, let’s execute example.sh:

$ bash example.sh
4 3 2 1

Here, we reverse the elements of the numbers_array array, store them in the reversed_numbers array, and then print the reversed_numbers array.

2.4. Using a Recursive Function

Another option that we can utilize is using a recursive function to reverse the array. To demonstrate, we’ll declare the function inside a shell script:

#!/bin/bash

# Initialize the original array
numbers_array=(1 2 3 4)

# Define a recursive function to reverse the array
reverse_array() {
    local array=("$@")
    local length=${#array[@]}
    if (( length > 0 )); then
        echo "${array[-1]}"
        reverse_array "${array[@]::length-1}"
    fi
}

# Capture the reversed elements
reversed_array=($(reverse_array "${numbers_array[@]}"))

# Print the original and reversed arrays
echo "Original Array: ${numbers_array[@]}"
echo "Reversed Array: ${reversed_array[@]}"

So, let’s describe the recursive function reverse array:

  • local array=(“$@”) – declares the local variable array to hold all the arguments passed to the function
  • local length=${#array[@]} – determines the number of elements in array
  • if (( length > 0 )) – checks that array is not empty
  • echo “${array[-1]}” – shows the last element of array
  • reverse_array “${array[@]::length-1}” – recursively calls the reverse_array function with all the array elements except for the last one

Now, let’s execute example.sh:

$ bash example.sh
Original Array: 1 2 3 4
Reversed Array: 4 3 2 1

Importantly, reversed_array=($(reverse_array “${numbers_array[@]}”)) executes the reverse_array function with numbers_array as its input and stores the output into reversed_array.

3. Conclusion

In this article, we explored approaches that we can utilize to reverse a Bash array.

Methods include using the tac command, implementing a for loop, employing a recursive function, and manually swapping array elements. So, understanding these methods increases our ability to perform Bash scripting. Additionally, we have the option to choose between the different techniques based on preference or use case.