Home > Back-end >  Makefile target to cd into a directory and run a go application
Makefile target to cd into a directory and run a go application

Time:11-01

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

CodePudding user response:

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
  • Related