Steve
Steve

Reputation: 159

Why do some commands return output but not others for exec.Command()

I am trying to figure out why some shell commands work with goloang exec.Command and others don't when they all return the same result when entered in terminal. I basically would like to use the same command for windows and mac binary (exec.Command("where", "go").Output()).

These specifically:

goInstalled, err := exec.Command("where", "go").Output() // does not return output on mac when compiled but does in terminal command. DOES return output on windows compiled.

goInstalled, err := exec.Command("which", "go").Output() // does not return output on mac when compiled but does in terminal command

goInstalled, err := exec.Command("command", "-v", "go").Output() // returns output when compiled and as terminal command (mac only)

I would like to use the same command for windows and mac (darwin) if possible rather than create two separate functions to check if things are installed on users machine.

Upvotes: 0

Views: 161

Answers (1)

syntaqx
syntaqx

Reputation: 2866

The main issue you're running into here is that exec.Command executes programs, where the commands you're trying to use are actually built-ins.

In order to use built-ins, you need to find them using exec.LookPath, and they're not generally available outside of a shell.

If you must, you can also execute the command from within a shell, by having a shell be first argument:

exec.Command("/bin/bash", "-c", "command -v foo")

Upvotes: 4

Related Questions