« Back to Index

Go: cross platform subprocess

View original Gist on GitHub

Tags: #go #windows #macos

cross-platform subprocess.go

// This works on macOS and also all these Window 10 variants: command prompt, Cygwin, PowerShell, WSL 🎉
package main

import (
	"fmt"
	"log"
	"os/exec"
	"runtime"
)

func main() {
	shell := "sh"
	flag := "-c"
	if runtime.GOOS == "windows" {
		shell = "cmd.exe"
		flag = "/C"
	}
	build := "go version && go version"

	cmd := exec.Command(shell, flag, build)
	out, err := cmd.Output()
	if err != nil {
		log.Fatal()
	}
	fmt.Println(string(out))
}