如何使用自定义环境变量执行”go build -ldflags”命令?

huangapple go评论68阅读模式
英文:

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

问题

我想在程序启动时打印构建时间,类似于以下代码:

package main

import "fmt"

var BuildTime string

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

我尝试通过设置一个环境变量来获取当前时间,使用命令 set bt (date),确保 echo $bt 能够显示时间。

然后使用 go build -ldflags "-X main.BuildTime=$bt" 进行构建,但是构建失败,并显示了一些链接器的用法,如下图所示:

如何使用自定义环境变量执行”go build -ldflags”命令?

我尝试了一些系统变量,如 $USER/$PWD/$TERM,例如 go build -ldflags "-X main.BuildTime=$USER",都能正常工作,为什么 $bt 不起作用呢?

我正在使用 fish shell,但我也尝试了 bash,问题是一样的。

英文:

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:

如何使用自定义环境变量执行”go build -ldflags”命令?

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

得分: 5

问题在于date中有空格,而其他环境变量没有空格。

为了处理可能包含空格的任何变量值,只需使用单引号'将构建参数包裹起来,如下所示:

# go build -ldflags "-X main.BuildTime=$bt"  # $bt值中的空格会导致解析错误

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

注意:如果你用单引号(')括起来的值本身可能包含单引号,则该值应该进行适当的转义

英文:

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.

huangapple
  • 本文由 发表于 2021年6月20日 07:23:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/68051479.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定