Getting a --version flag for Cobra CLIs in Go, built with GoReleaser

Featured image for sharing metadata for article

Update 2023-05-27: If you're looking for an option that works with GoReleaser and go installs, check out my more recent post Getting a --version flag for Cobra CLIs in Go.

As part of working on my new Go CLI dmd, I wanted to implement a --version flag to be able to check what version is currently installed.

I'd started looking at how to do this after I spotted that GoReleaser populates main.version ldflags which mean that you can easily consume the data introduced.

I started looking around for solutions, finding Go Version for Cobra Projects and just as I was looking to implement this, I found that Cobra now supports it out-of-the-box if you set the rootCmd.Version.

So how do we do this?

The below examples can be found in an example repo on

Firstly, in our main.go, we can ensure that there are variables set to receive the values from the ldflags, and pass them to a SetVersionInfo method:

package main

import ""

var (
	version = "dev"
	commit  = "none"
	date    = "unknown"

func main() {
	cmd.SetVersionInfo(version, commit, date)

This then calls this snippet to allow us to set the rootCmd's versioning information:

func SetVersionInfo(version, commit, date string) {
	rootCmd.Version = fmt.Sprintf("%s (Built on %s from Git SHA %s)", version, date, commit)

If we build it normally with go build and then invoke it, we'll not see any version data:

go build
./go-cobra-goreleaser-version-example --version
go-cobra-goreleaser-version-example version dev (Built on unknown from Git SHA none)

However, if we use goreleaser to build it, we do see the version info:

goreleaser release --snapshot --clean
# where $PLATFORM is the OS platform you're running from
./dist/go-cobra-goreleaser-version-example_$PLATFORM/go-cobra-goreleaser-version-example --version
go-cobra-goreleaser-version-example version 0.0.0-SNAPSHOT-none (Built on 2023-02-27T17:09:11Z from Git SHA none)

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#blogumentation #go #goreleaser.

This post was filed under articles.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.