Skip to content

Instantly share code, notes, and snippets.

@michelson
Created January 26, 2015 03:57
Show Gist options
  • Save michelson/640b1db906e9657f519d to your computer and use it in GitHub Desktop.
Save michelson/640b1db906e9657f519d to your computer and use it in GitHub Desktop.
cmd exec
package main
import (
"bytes"
"flag"
"fmt"
//"log"
"os"
"os/exec"
"strings"
)
//usage: go run ./main.go -cmd="#{cmd}"
func main() {
cmd := flag.String("cmd", "foo", "a string")
flag.Parse()
commands := strings.Split(*cmd, ";")
for _, num := range commands {
ExecCmd(num)
}
os.Exit(0)
}
func ExecCmd(cmd string) string {
//args := strings.Split(cmd, " ")
c := exec.Command("sh", "-c", cmd)
//c := exec.Command(args[0], args[1:]...)
c.Stdin = strings.NewReader("some input")
var out bytes.Buffer
c.Stdout = &out
err := c.Run()
if err != nil {
//log.Fatal(err)
//fmt.Printf(fmt.Sprint(err), ":", out.String())
fmt.Println(cmd)
fmt.Println("out:", out.String())
fmt.Printf("err:", fmt.Sprint(err) )
os.Exit(1)
}
//fmt.Printf(strings.Join(args, " "), "cmd response: %q\n", out.String())
//fmt.Printf("cmd: ", strings.Join(args, " ") )
fmt.Printf(out.String())
return out.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment