Last active
November 4, 2024 18:35
-
-
Save andkirby/54204328823febad9d34422427b1937b to your computer and use it in GitHub Desktop.
Semantic versions sorting in bash.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Download this gist | |
# curl -Ls https://gist.github.com/andkirby/54204328823febad9d34422427b1937b/raw/semversort.sh | bash | |
# And run: | |
# $ semversort 1.0 1.0-rc 1.0-patch 1.0-alpha | |
# or in GIT | |
# $ semversort $(git tag) | |
# Using pipeline: | |
# $ echo 1.0 1.0-rc 1.0-patch 1.0-alpha | semversort | |
# | |
# 2016-11-03 | |
# Released. | |
# 2020-03-10 | |
# Changed regular part from "[A-z]" to "[A-Za-z]" | |
set -o errexit | |
set -o pipefail | |
set -o nounset | |
#set -o xtrace | |
# Script running with pipeline | |
if [ -z "${BASH_SOURCE[0]:-}" ]; then | |
__dir=/usr/local/bin | |
if [ ! -d ${__dir} ]; then | |
__dir=/usr/bin | |
fi | |
__file=${__dir}/semversort | |
curl -Ls https://gist.github.com/andkirby/54204328823febad9d34422427b1937b/raw/semversort.sh -o ${__file} && \ | |
chmod u+x ${__file} && \ | |
echo 'Semantic version sort: '${__file} && \ | |
exit 0 | |
exit 1 | |
fi | |
if [ -t 0 ]; then | |
versions_list=$@ | |
else | |
# catch pipeline output | |
versions_list=$(cat) | |
fi | |
version_weight () { | |
echo -e "$1" | tr ' ' "\n" | sed -e 's:\+.*$::' | sed -e 's:^v::' | \ | |
sed -re 's:^[0-9]+(\.[0-9]+)+$:&-stable:' | \ | |
sed -re 's:([^A-Za-z])dev\.?([^A-Za-z]|$):\1.10.\2:g' | \ | |
sed -re 's:([^A-Za-z])(alpha|a)\.?([^A-Za-z]|$):\1.20.\3:g' | \ | |
sed -re 's:([^A-Za-z])(beta|b)\.?([^A-Za-z]|$):\1.30.\3:g' | \ | |
sed -re 's:([^A-Za-z])(rc|RC)\.?([^A-Za-z]|$)?:\1.40.\3:g' | \ | |
sed -re 's:([^A-Za-z])stable\.?([^A-Za-z]|$):\1.50.\2:g' | \ | |
sed -re 's:([^A-Za-z])pl\.?([^A-Za-z]|$):\1.60.\2:g' | \ | |
sed -re 's:([^A-Za-z])(patch|p)\.?([^A-Za-z]|$):\1.70.\3:g' | \ | |
sed -r 's:\.{2,}:.:' | \ | |
sed -r 's:\.$::' | \ | |
sed -r 's:-\.:.:' | |
} | |
tags_orig=(${versions_list}) | |
tags_weight=( $(version_weight "${tags_orig[*]}") ) | |
keys=$(for ix in ${!tags_weight[*]}; do | |
printf "%s+%s\n" "${tags_weight[${ix}]}" ${ix} | |
done | sort -V | cut -d+ -f2) | |
for ix in ${keys}; do | |
printf "%s\n" ${tags_orig[${ix}]} | |
done |
@yurivict yes, it's not intended to use various formats, but only Semantic Versions format which is MAJOR.MINOR.PATCH.
Like it described in https://semver.org/
Thanks for this note anyway, it's good to know edge cases.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This script produces wrong result.
Example: