Bash (Scripting) - Sorting Lists

by
Jeremy Canfield |
Updated: March 14 2023
| Bash (Scripting) articles
Let's say you have an list named fruit that contains the following values.
fruit=(banana apple orange apple grapes)
A for loop can be used to iterate over each item in the list, like this.
for myFruit in ${fruit[@]}; do
echo $myFruit
done
Which should return the following. Notice the list is NOT sorted alphabetically.
banana
apple
orange
apple
grape
Here is how you can sort the list alphabetically.
IFS=$'\n'
fruit=($(sort <<<"${fruit[*]}"))
unset IFS
A for loop can be used to iterate over each item in the list.
for myFruit in ${sorted[@]}; do
echo $myFruit
done
Which should return the following. Notice that the output is now sorted alphabetically.
apple
apple
banana
grape
orange
Notice apple is listed twice. The -u or --uniq flag can be included to only return unique values.
fruit=($(sort --uniq <<<"${fruit[*]}"))
Let's say you have an list that containers numbers (integers).
foo=(1 0 17 5)
In this scenario, you will want to include the -n or --numeric-sort to sort the list numerically.
IFS=$'\n'
fruit=($(sort --numeric-sort <<<"${fruit[*]}"))
unset IFS
Did you find this article helpful?
If so, consider buying me a coffee over at