Skip to content

Instantly share code, notes, and snippets.

@dialogbox
Last active August 17, 2021 08:44
Show Gist options
  • Save dialogbox/71177892ac6d3879c563 to your computer and use it in GitHub Desktop.
Save dialogbox/71177892ac6d3879c563 to your computer and use it in GitHub Desktop.
popen style simple command execution in golang for Windows/Linux/Unix
package main
import (
"fmt"
"os/exec"
"strings"
)
func runcmd(command string) string {
var shell, flag string
if runtime.GOOS == "windows" {
shell = "cmd"
flag = "/c"
} else {
shell = "/bin/sh"
flag = "-c"
}
out, err := exec.Command(shell, flag, command).Output()
if err != nil {
panic(err)
}
return string(out)
}
func main() {
fmt.Println(strings.TrimSpace(runcmd("hostname")))
fmt.Println(strings.TrimSpace(runcmd("netstat -an | grep 80"))) // unix
fmt.Println(strings.TrimSpace(runcmd("netstat -an | findstr 80"))) // windows
}
@idiotzavant
Copy link

works for me. Thanks.

@bbbiggest
Copy link

works for me, too. Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment