Skip to content

Instantly share code, notes, and snippets.

@danesparza
Last active June 28, 2023 20:41
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save danesparza/a651ac923d6313b9d1b7563c9245743b to your computer and use it in GitHub Desktop.
Save danesparza/a651ac923d6313b9d1b7563c9245743b to your computer and use it in GitHub Desktop.
Go exec.Command example
package main
import (
"bytes"
"fmt"
"os/exec"
"strings"
)
func main() {
// Split the entire command up using ' -' as the delimeter
parts := strings.Split(`pushnotify.exe --to=gqukgkJyLtchaLE41WUEJ2qFM7Q3tb --title=New Plex content --message={showname} season {showseasonnumber} episode {showepisodenumber} just landed on Plex --sound=magic`, " -")
// The first part is the command, the rest are the args:
head := parts[0]
args := parts[1:len(parts)]
// Format the command
cmd := exec.Command(head, args...)
/*
// Sanity check -- just print out the detected args:
for _, arg := range cmd.Args {
log.Println(arg)
}
*/
// Sanity check -- capture stdout and stderr:
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
// Run the command
cmd.Run()
// Output our results
fmt.Printf("Result: %v / %v", out.String(), stderr.String())
}
@mtamali
Copy link

mtamali commented Jun 8, 2018

Hi
Thanks for sharing the code

@joaowiciuk
Copy link

Thanks for sharing!

@TangoEnSkai
Copy link

thanks for sharing the code

@pmgexpo17
Copy link

Thanks for sharing

A default use case perhaps is connecting stdout and stderr to the related os files, like so :

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

//	Run the command
cmd.Run()

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