shellsorting

How to sort string array in descending order in Bash?


let's say I have an array:

nameArr=("Leia", "Darth Vader", "Anakin", "Han Solo", "Yoda")

and I would like to sort in descending order. How could I do it in Bash shell scripting? In ascending order I am using command:

arrAsc=($(for l in ${nameArr[@]}; do echo $l; done | sort))

Thanks a lot for help!


Solution

  • You can do so fairly easily making use of IFS (internal field separator), sort -r, and a little help from printf. Using command substitution you can output and sort the array and then simply read the sorted results back into nameArr. For instance:

    #!/bin/bash
    
    nameArr=("Leia", "Darth Vader", "Anakin", "Han Solo", "Yoda")
    
    IFS=$'\n'           ## only word-split on '\n'
    nameArr=( $(printf "%s\n" ${nameArr[@]} | sort -r ) )  ## reverse sort
    
    declare -p nameArr  ## simply output the array
    

    Example Use/Output

    Calling the script results in the following:

    $ bash revarr.sh
    declare -a nameArr='([0]="Yoda" [1]="Leia," [2]="Han Solo," [3]="Darth Vader," [4]="Anakin,")'
    

    note: don't forget to restore the default IFS=$' \t\n' (space, tab, newline) when done with the sort if your script continues.