
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
Here is how you can sort a list that contains IP addresses.
ip_array=("192.168.1.10" "10.0.0.1" "192.168.1.2" "172.16.0.1" "10.0.0.100")
sorted_ips=($(printf "%s\n" "${ip_array[@]}" | sort -t . -n -k 1,1 -k 2,2 -k 3,3 -k 4,4))
for ip in "${sorted_ips[@]}"; do
echo "$ip"
done
Did you find this article helpful?
If so, consider buying me a coffee over at