0

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"

4 Answers 4

3

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")
Sign up to request clarification or add additional context in comments.

Comments

1
releases=( "1.3.1243" "2.0.1231" "0.8.4454" "1.2.4124" "1.2.3231" "0.9.5231" )
sorted=( $(echo ${releases[*]} | sed 's/ /\n/g' | sort -t. -k1,1rn -k2,2rn -k3,3rn) )
echo ${sorted[*]}

This uses sed and sort to reverse sort the items, using . as the field separator, and treating each field as numeric:

2.0.1231 1.3.1243 1.2.4124 1.2.3231 0.9.5231 0.8.4454

Comments

1
releases=( "1.3.1243" "2.0.1231" "0.8.4454" "1.2.4124" "1.2.3231" "0.9.5231"
readarray -t sorted < <(printf '%s\n' "${releases[@]}" | sort -Vr)
declare -p sorted
declare -a sorted=([0]="2.0.1231" [1]="1.3.1243" [2]="1.2.4124" [3]="1.2.3231" [4]="0.9.5231" [5]="0.8.4454")

Comments

0

In Git, the version numbers are usually set using tags.

The following command will list the tags and sort them in descending order (with the flag -r)

git tag | sort -rV

The flag 'V' which stands for 'natural sort of (version) numbers within text is necessary for 'v10.0' to be on top of 'v9.0'.

To extract the last version number, use the following command:

git tag | sort -rV | head -n 1

1 Comment

Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. Would you kindly edit your answer to include additional details for the benefit of the community?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.