Makefile目标:进入一个目录并运行一个Go应用程序。

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

Makefile target to cd into a directory and run a go application

问题

我有需要进入特定目录,然后简单地运行 go run main.go 来启动我的应用程序。我有以下内容:

stand-app: |
	$(info 正在启动应用程序进行本地测试)
	cd $(PWD)/cmd/myapp
	go run main.go

当我运行目标时,我得到以下结果:

go run main.go
stat main.go: 没有那个文件或目录
make: *** [stand-app] 错误 1

但是位置是正确的,我可以通过进入该目录并运行命令来完成这些步骤。我做错了什么?

谢谢。

英文:

I have the need to cd to a specific directory and then simply run go run main.go and stand up my application. I have the following:

stand-app: |
	$(info Booting up the app for local testing)
	cd $(PWD)/cmd/myapp
	go run main.go

When I run the target I get the following:

go run main.go
stat main.go: no such file or directory
make: *** [stand-app] Error 1

But the location is correct and I can simply do the steps by cd onto that directory and running the command. Where am I going wrong?

Thank you

答案1

得分: 2

每个逻辑行在一个不同的shell中运行。当前工作目录是shell的属性;当shell退出时,对工作目录的任何更改也会消失。所以,你的cd ...是一个空操作:它在该shell中更改了工作目录,然后该shell退出,下一个shell以原始工作目录启动。

将这两行合并为一行逻辑行,可能是这样的:

stand-app:
        $(info 正在启动本地测试应用程序)
        cd $(PWD)/cmd/myapp && go run main.go

只是提醒一下:PWD对于make来说并没有特殊之处。如果你从中调用make的shell设置了它,它将有一个值;如果你从中调用make的shell没有设置它(或者如果在父shell中没有正确设置它),它将没有值(或者如果设置不正确,它将有错误的值)。你可能想使用make的CURDIR变量代替:

stand-app:
        $(info 正在启动本地测试应用程序)
        cd '$(CURDIR)/cmd/myapp' && go run main.go
英文:

Every logical line in a recipe is run in a different shell. The current working directory is an attribute of the shell; when the shell goes away any change to the working directory goes away as well. So, your cd ... is a no-op: it changes the working directory in that shell, then the shell exits and the next shell starts with the original working directory.

Combine these two lines into one logical line; maybe something like:

stand-app:
        $(info Booting up the app for local testing)
        cd $(PWD)/cmd/myapp && go run main.go

Just to remind: PWD is in no way special to make. It will have a value if the shell you invoked make from sets it, and it will have no value if the shell you invoked make from doesn't set it (or it will have the wrong value if it's not set correctly in the parent shell). You probably want to use make's CURDIR variable instead:

stand-app:
        $(info Booting up the app for local testing)
        cd '$(CURDIR)/cmd/myapp' && go run main.go

huangapple
  • 本文由 发表于 2022年11月1日 04:53:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/74269018.html
匿名

发表评论

匿名网友

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

确定