英文:
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"
进行构建,但是构建失败,并显示了一些链接器的用法,如下图所示:
我尝试了一些系统变量,如 $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:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论