Bash Array Sorting



Bash Array Sorting

In Bash scripting, sorting an array is useful for various tasks that require arranging the elements of an array in a specific order.


Syntax

sorted_array=( $(for i in "${array[@]}"; do echo $i; done | sort) )

The basic syntax involves using a combination of a for loop and the sort command to sort the elements of the array and store them in a new array.


Example Bash Array Sorting

Let's look at some examples of how to sort an array in Bash:

1. Sort an Array of Strings

This script initializes an array with string elements, sorts the array, and prints the sorted array.

#!/bin/bash

array=("banana" "apple" "cherry")
sorted_array=( $(for i in "${array[@]}"; do echo $i; done | sort) )
echo "Sorted array: ${sorted_array[@]}"

In this script, the array variable array is initialized with the elements 'banana', 'apple', and 'cherry'. The for loop iterates over the elements of the array, and the sort command sorts them. The sorted elements are stored in the sorted_array variable. The script then prints the sorted array.

Sort an array of strings in Bash

2. Sort an Array of Numbers

This script initializes an array with numeric elements, sorts the array in numerical order, and prints the sorted array.

#!/bin/bash

array=(3 1 2)
sorted_array=( $(for i in "${array[@]}"; do echo $i; done | sort -n) )
echo "Sorted array: ${sorted_array[@]}"

In this script, the array variable array is initialized with the elements 3, 1, and 2. The for loop iterates over the elements of the array, and the sort -n command sorts them numerically. The sorted elements are stored in the sorted_array variable. The script then prints the sorted array.

Sort an array of numbers in Bash

3. Sort an Array with Elements from User Input

This script initializes an array with elements from user input, sorts the array, and prints the sorted 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
sorted_array=( $(for i in "${array[@]}"; do echo $i; done | sort) )
echo "Sorted array: ${sorted_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, and the sort command sorts them. The sorted elements are stored in the sorted_array variable. The script then prints the sorted array.

Sort an array with elements from user input in Bash

Conclusion

Sorting an array in Bash is a fundamental task for arranging the elements of an array in a specific order in shell scripting. Understanding how to sort arrays can help you manage and manipulate arrays effectively in your scripts.