-4

I have quite a simple Go app called myApp that is supposed to launch a new Terminal window on macOS:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    err := exec.Command("open", "-a", "Terminal", "/Users/ns/go/").Run()
    if err != nil {
        fmt.Println(err)
    }
}

However, when I run the app I get the following output:

ns:~/go/src/github.com/nevadascout/myApp $ go install && myApp
exit status 1

If I run the command (open -a Terminal /Users/ns/go/) in the terminal manually, it works.
What am I missing?

nevada_scout
  • 971
  • 3
  • 16
  • 37
  • So your original question had two problems (tilde expansion, and calling a built-in). Calling bash directly solves both. – Jonathan Hall Jul 14 '19 at 10:37

1 Answers1

2

From the docs:

Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.

So you need to run bash -c command and pass above command as argument. Something like this:

exec.Command("bash", "-c", "open", "-a", "Terminal", "~/go/").Run()

For windows you should use cmd /C. Example:

exec.Command("cmd", "/C", ...)
novalagung
  • 10,905
  • 4
  • 58
  • 82
  • 1
    Thanks! This was almost right, the part after the "-c" needed to be one argument instead of multiple ones: `exec.Command("bash", "-c", "open -a Terminal /Users/ns/go/").Run()` – nevada_scout Jul 14 '19 at 10:22