使用os / exec命令从Windows交叉编译到Linux

The title mostly says it. I know that I can do

set GOOS=linux
set GOARCH=amd64

in cmd before I go build, but I'm trying to write a build script and do it all with exec.Command.

My go build -o etc works with exec.Command (it builds), but when printing out GOOS in a test script after either of this commands:

cmd := exec.Command("set", "GOOS=linux")
// OR
cmd := exec.Command("set GOOS=linux")

I get windows.

Any ideas? Thanks!

I strongly suggest you just use a tool like Gox instead. It cross-compiles into every supported build target by just executing gox. It also has options if you only want to build for certain targets.

As for the code you're asking about, exec.Command doesn't create a new process, or really do anything other than create a Cmd struct. The os/exec documentation (specifically the docs for the Command function) has an example of what you seem to be trying to do- execute another program with custom environment variable assignments... see the Example (Environment) section of the linked documentation and try to follow that structure if you still want to cross-compile your way.