Skip to main content
In this lesson, you’ll learn how to append elements to a Bash array and then sort that array using standard Unix utilities. We’ll cover:
  • Appending items with the += notation
  • Sorting array elements by printing each one on a new line
  • Capturing sorted output in a new array for easy comparison

1. Appending Elements with +=

Bash arrays support the += operator to add one or more items at the end of an existing array. Here’s an example:
Save this as example2.sh and run:

2. Sorting an Array with printf & sort

Bash doesn’t have a built-in array sort, but you can leverage the Unix sort command. Since sort expects one item per line, use printf to split space-separated elements:
Do not enclose each item in quotes (e.g., "a" "b"), or printf will treat them as single arguments and won’t split them into lines.
Output:
You can apply the same method to numeric arrays:
Running sort_numbers.sh:

3. Displaying Unsorted and Sorted Arrays

To compare the original and sorted array side by side, capture the sorted output in a new array via command substitution:
Running sort_ex2.sh produces:
The image shows a comparison between an unsorted array (4, 2, 0, 6, 8, 1) and its sorted version (0, 1, 2, 4, 6, 8) with a lightbulb icon above.

Summary

Watch Video