Skip to main content
Versions of versions

Howto get the next semver version number in a bash script

In my projects, I often encounter situations where I need to update the version number of the project before making a release. I follow the Semantic Versioning (Semver) standard for versioning. In this blog post, I’ll demonstrate how to retrieve the next Semver version number using a Bash script. This script allows me to update the version number before finalizing the release, ensuring that the release commit and tags are correctly synchronized.

The Problem:

Previously, I would release a new version, note down the version number, update various files and documentation, and then update the release commit. This approach often resulted in tags that weren’t aligned with the actual release commit, causing confusion.

The Solution:

To address this issue, I created a Bash script that takes the current version number (as it is defined in the package.json) and increments it based on the release type (patch/minor/major). This way, I can update the version number before the release is complete and use the updated version number in the release commit without any complications.

Here’s a Bash function that can be used within a library or Bash script:

 1#!/bin/bash
 2
 3get_next_version() {
 4  local increment_type="$1"
 5  local RE='[^0-9]*\([0-9]*\)[.]\([0-9]*\)[.]\([0-9]*\)\([0-9A-Za-z-]*\)'
 6
 7  if [ -z "$increment_type" ]; then
 8    increment_type="patch"
 9  fi
10
11  local base=$(node -pe 'require("./package.json")["version"]')
12
13  local MAJOR=$(echo $base | sed -e "s#$RE#\1#")
14  local MINOR=$(echo $base | sed -e "s#$RE#\2#")
15  local PATCH=$(echo $base | sed -e "s#$RE#\3#")
16
17  case "$increment_type" in
18  major)
19    ((MAJOR += 1))
20    ((MINOR = 0))
21    ((PATCH = 0))
22    ;;
23  minor)
24    ((MINOR += 1))
25    ((PATCH = 0))
26    ;;
27  patch)
28    ((PATCH += 1))
29    ;;
30  esac
31
32  local NEXT_VERSION="$MAJOR.$MINOR.$PATCH"
33  echo "$NEXT_VERSION"
34}

The big trick is to use the node command to read the version number from the package.json file and then parse out the particles with some sed magic. This way, we don’t have to worry about parsing the file ourselves. The node command is available on most systems, so this approach should work for most projects.

1node -pe 'require("./package.json")["version"]'

This command is useful enough to get anything out of the package.json file.

You can use this function as follows:

1next_version=$(get_next_version "minor")
2echo "Next version: $next_version"

This call will return the next minor release version. For example, if the current version is 1.1.2, it will become 1.2.0. Similarly, 1.0.123 will become 1.1.0, and 1.0.0 will become 1.1.0.

You can also use “major” or “patch” as options to specify the type of release increment.

Now, it’s time to update my release hooks everywhere and streamline my versioning process! 😄

Back to top