1

I'm writing a Makefile for a Go application, and would like to be able to pass in an environment variable to specify debug flags for the go build command.

The script for building the service without debug flags looks like this:

cd ./authentication-service && env GOOS=linux CGO_ENABLED=0 go build -o ${AUTH_BINARY} ./cmd/api

I'd like to be able to inject these flags after the go build part of the command, like so:

cd ./authentication-service && env GOOS=linux CGO_ENABLED=0 go build -gcflags=all="-N -l" ${AUTH_BINARY} ./cmd/api

I've read that you can use the echo command to send arguments like this, but when I try the following, I get an error

cd ./authentication-service && env GOOS=linux CGO_ENABLED=0 go build `if [ "${DEBUG}" = 'auth' ]; then echo '-gcflags=all="-N -l"'; fi` -o authApp ./cmd/api
invalid value "all=\"-N" for flag -gcflags: unterminated " string
usage: go build [-o output] [build flags] [packages]
Run 'go help build' for details.
make: *** [build_broker] Error 2

How can I conditionally supply -gcflags=all="-N -l" to this build command when a certain environment variable check returns true?

kostix
  • 51,517
  • 14
  • 93
  • 176
Harrison Cramer
  • 3,792
  • 9
  • 33
  • 61
  • Does this answer your question? [Why does shell ignore quoting characters in arguments passed to it through variables?](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) – tjm3772 Nov 20 '22 at 16:41
  • Even though you're not exactly using a variable, the basic problem is the same - syntax parsing happens before expansions are processed in your command line, so the quotes embedded in whatever you echo are only treated as literal characters and have no syntactic value. This means word splitting will split `-gcflags=all="-N -1"` into `-gcflags=all="-N` and `-1"` which causes the unterminated error. – tjm3772 Nov 20 '22 at 16:44
  • See also [BashFAQ/050: I'm trying to put a command in a variable, but the complex cases always fail!](http://mywiki.wooledge.org/BashFAQ/050) – tjm3772 Nov 20 '22 at 16:47
  • The usual solution is to change the `Makefile` so that you can override options at `make` time. But you want that for portability, not flexibility. The debug target should be separate so that you can't mistake the debug binary for a production binary. – tripleee Nov 20 '22 at 17:01
  • Ended up using a normal bash if/else directly in the makefile rather than trying to inline this because the target binary was also different in production and debugging.Thanks all. – Harrison Cramer Nov 21 '22 at 13:36

0 Answers0