- 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:
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.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:sort_ex2.sh produces:

Summary
| Task | Command Example |
|---|---|
| Append elements | array+=("item1" "item2") |
| Sort an array | printf "%s\n" "${array[@]}" | sort |
| Capture sorted output | sorted=( $(printf "%s\n" "${array[@]}" | sort) ) |