Last active
August 17, 2021 08:44
-
-
Save dialogbox/71177892ac6d3879c563 to your computer and use it in GitHub Desktop.
popen style simple command execution in golang for Windows/Linux/Unix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
works for me. Thanks.