Search code examples
bashsortingsh

How to sort release version string in descending order with Bash


I have a list of release version strings that looks something like this:

releases=( "1.3.1243" "2.0.1231" "0.8.4454" "1.2.4124" "1.2.3231" "0.9.5231" )

How can I use bash to sort my releases array such that the array is sorted in descending order (so the value on the left has the highest precedence).

So the after sorting, the example above would be in the following order:

"2.0.1231", "1.3.1243", "1.2.4124", "1.2.3231", "0.9.5231", "0.8.4454"

Solution

  • You can actually do it quite easily with command substitution and the version sort option to sort, e.g.

    releases=($(printf "%s\n" "${releases[@]}" | sort -rV))
    

    (note: the printf-trick simply separates the elements on separate lines so they can be piped to sort for sorting. printf "%s\n", despite having only one "%s" conversion specifier, will process all input)

    Now releases contains:

    releases=("2.0.1231" "1.3.1243" "1.2.4124" "1.2.3231" "0.9.5231" "0.8.4454")