3

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.

aj3423
  • 2,003
  • 3
  • 32
  • 70
  • 1
    I'm using bash and no matter what I try, if the variable contains spaces it just won't work. Maybe try `FLAGS="-X main.BuildTime"; FLAGS="$FLAGS=$(date '+%Y-%m-%d_%H-%M')"; go build -ldflags "$FLAGS"` – xarantolus Jun 20 '21 at 09:42
  • @xarantolus, this should be the answer, and the script for fish shell is `set x (date '+%Y-%m-%d_%H-%M-%S'); set f "-X main.BuildTime=$x"; go build -ldflags "$f"`, thanks. – aj3423 Jun 20 '21 at 10:56

1 Answers1

5

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.

colm.anseo
  • 19,337
  • 4
  • 43
  • 52