Incrementing a Semantic Version String in Bash
2019 April 30

I wrote a bash function that takes a semantic version string and bumps the version number. It supports all 3 layers. I needed it for the deploy script I was working on. It’s fairly trivial, I just thought I would share it.

Semantic versioning is a 3 number version string consisting of a major, minor, and revision number. This function allows you to bump any one of those numbers and reset the earlier numbers. Semantic versioning tends to be a fairly popular scheme and is mandatory for certain frameworks like WordPress.

# $1 - semver string
# $2 - level to incr {release,minor,major} - release by default
function incr_semver() { 
    IFS='.' read -ra ver <<< "$1"
    [[ "${#ver[@]}" -ne 3 ]] && echo "Invalid semver string" && return 1
    [[ "$#" -eq 1 ]] && level='release' || level=$2

    release=${ver[2]}
    minor=${ver[1]}
    major=${ver[0]}

    case $level in
        release)
            release=$((release+1))
        ;;
        minor)
            release=0
            minor=$((minor+1))
        ;;
        major)
            release=0
            minor=0
            major=$((major+1))
        ;;
        *)
            echo "Invalid level passed"
            return 2
    esac
    echo "$major.$minor.$release"
}

Remember you can also subscribe using RSS at the top of the page!

Share this on → Mastodon Twitter LinkedIn Reddit

A selected list of related posts that you might enjoy:

*****
Written by Henry J Schmale on 2019 April 30
Hit Counter