Bootstrap FreeKB - Bash (Scripting) - Sorting Lists
Bash (Scripting) - Sorting Lists

Updated:   |  Bash (Scripting) articles

Let's say you have an list named fruit that contains the following values.

fruit=(banana apple orange apple grapes)

 

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

 

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 Buy Me A Coffee



Comments


Add a Comment


Please enter b36fed in the box below so that we can be sure you are a human.