Skip to content

Instantly share code, notes, and snippets.

@r3vit
Created September 8, 2016 12:13
Show Gist options
  • Save r3vit/172708daf41f9a1ffdd0d6e795f72d58 to your computer and use it in GitHub Desktop.
Save r3vit/172708daf41f9a1ffdd0d6e795f72d58 to your computer and use it in GitHub Desktop.
Exec command line commands in go
package main
import (
"fmt"
"log"
"os/exec"
"strings"
)
func main() {
//commands
cmdProg := "ls"
cmdArgs := [...]string{"-a", "l"}
cmdArgsString := strings.Join(cmdArgs[:], "")
cmd := cmdProg + " " + cmdArgsString
//is cmdProg installed?
path, err := exec.LookPath(cmdProg)
if err != nil {
log.Fatal("You need to install " + cmdProg + " before :)")
} else {
fmt.Println(cmdProg + " found at: " + path + "\n ---- START ----")
}
//exec command
out, err := exec.Command(cmdProg, cmdArgsString).CombinedOutput()
if err != nil {
log.Fatal(err)
}
fmt.Println("Executing ("+cmd+"): \n ", string(out))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment