Thursday, August 13, 2026
HomeGolangGo env: give details about the absence of a env variable -...

Go env: give details about the absence of a env variable – Technical Dialogue


The cross-platform resolution could be this, utilizing a small compiled Go program:

package deal primary

import (
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
)

func primary() {
	if len(os.Args) != 2 {
		fmt.Fprintln(os.Stderr, "utilization: checkenv VARNAME")
		os.Exit(2)
	}
	identify := os.Args[1]

	out, err := exec.Command("go", "env", "-json").Output()
	if err != nil {
		fmt.Fprintln(os.Stderr, "error operating go env:", err)
		os.Exit(1)
	}

	var vars map[string]string
	if err := json.Unmarshal(out, &vars); err != nil {
		fmt.Fprintln(os.Stderr, "error parsing json:", err)
		os.Exit(1)
	}

	val, okay := vars[name]
	if !okay {
		fmt.Fprintf(os.Stderr, "ERROR - unknown go command variable %sn", identify)
		os.Exit(1)
	}
	fmt.Printf("OK - Worth of %s is %s:", identify, val)
}

The benefit is that it runs identically on Home windows and Linux, with no exterior dependencies (no jq, no python) — simply Go, which is already put in anyway. You compile it as soon as and use the binary from then on.

Identify the file checkenv.go. The compiled binary can be checkenv (on Home windows, checkenv.exe).

You possibly can run it with out compiling (for testing):

go run checkenv.go VARNAME

Or compiled, for repeated use:

go construct -o checkenv checkenv.go

Then transfer the binary (checkenv or checkenv.exe) right into a folder that’s in your PATH — for instance ~/go/bin on Linux/macOS, or any folder you’ve manually added to PATH on Home windows.
From there you may run it from anyplace, straight:

checkenv VARNAME

Examples :

checkenv GOPATH
OK – Worth of GOPATH is /dwelling/consumer/go:
checkenv GOTEST
ERROR – unknown go command variable GOTEST

If you happen to run the command with no arguments or with multiple:

checkenv
utilization: checkenv VARNAME

The messages (“ERROR – unknown go command variable X” and “OK – Worth of X is Y”) may be modified freely to no matter wording is most well-liked.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments