Skip to content

Instantly share code, notes, and snippets.

@maxrimue
Created Jul 24, 2015
Embed
What would you like to do?
Compare semantic versions in pure bash
#!/bin/bash
# Assume we have two semantic versions that we want to compare:
version1=0.12.0
version2=1.15.5
# First, we replace the dots by blank spaces, like this:
version1=${version1//./ }
version2=${version2//./ }
# If you have a "v" in front of your versions, you can get rid of it like this:
version1=${version1//v/}
version2=${version2//v/}
# Now we have "0 12 0" and "1 15 5"
# So, we just need to extract each number like this:
patch1=$(echo $version1 | awk '{print $3}')
minor1=$(echo $version1 | awk '{print $2}')
major1=$(echo $version1 | awk '{print $1}')
patch2=$(echo $version2 | awk '{print $3}')
minor2=$(echo $version2 | awk '{print $2}')
major2=$(echo $version2 | awk '{print $1}')
# And now, we can simply compare the variables, like:
[ $major1 -lt $major2 ] && echo "That's true"
[ $minor1 -gt $minor2 ] || echo "That's wrong"
@VishwasShashidhar

This comment has been minimized.

Copy link

@VishwasShashidhar VishwasShashidhar commented Aug 28, 2018

Nice script 👍

@gtrabanco

This comment has been minimized.

Copy link

@gtrabanco gtrabanco commented Mar 17, 2021

platform::semver_compare() {
  if [ -z "${1:-}" ] || [ -z "${2:-}" ]; then
    return 1
  fi

  normalize_ver() {
    local version
    version="${1//./ }"
    echo "${version//v/}"
  }

  compare_ver() {
    [[ $1 -lt $2 ]] && echo -1 && return
    [[ $1 -gt $2 ]] && echo 1 && return

    echo 0
  }

  v1="$(platform::normalize_ver "${1:-}")"
  v2="$(platform::normalize_ver "${2:-}")"

  major1="$(echo "$v1" | awk '{print $1}')"
  major2="$(echo "$v2" | awk '{print $1}')"

  minor1="$(echo "$v1" | awk '{print $2}')"
  minor2="$(echo "$v2" | awk '{print $2}')"

  patch1="$(echo "$v1" | awk '{print $3}')"
  patch2="$(echo "$v2" | awk '{print $3}')"

  compare_major="$(platform::compare_ver "$major1" "$major2")"
  compare_minor="$(platform::compare_ver "$minor1" "$minor2")"
  compare_patch="$(platform::compare_ver "$patch1" "$patch2")"

  if [[ $compare_major -ne 0 ]]; then
    echo "$compare_major"
  elif [[ $compare_minor -ne 0 ]]; then
    echo "$compare_minor"
  else
    echo "$compare_patch"
  fi
}

It was done using this guide for a WIP feature for https://github.com/codelytv/dotly

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment