How to "go build -ldflags" with custom environment variable

Viewed 1548

I want to print the build time when program starts, like:

package main

import "fmt"

var BuildTime string

func main() {
    fmt.Println(BuildTime)
}

I tried set an environment variable to current time by set bt (date), make sure echo $bt shows the time.

Then build with go build -ldflags "-X main.BuildTime=$bt", but it fails to build and shows the usage of some linker, like:

err

I tried some system variable like $USER/$PWD/$TERM, like go build -ldflags "-X main.BuildTime=$USER", all work fine, why not work for $bt ?

I'm using fish shell, but I also tried bash, same problem.

1 Answers

The issue is that date has spaces - whereas the other env var's do not.

To account for any variable value that may have spaces, just wrap the build arg with single quotes ' like so:

# go build -ldflags "-X main.BuildTime=$bt"  # spaces in $bt value will lead to parse errors

go build -ldflags "-X 'main.BuildTime=$bt'"

Note: if the value you're enclosing with single-quotes (') may itself have a single-quote - then the value should be properly escaped.

Related