Skip to content

Instantly share code, notes, and snippets.

@pgbytes
Created February 15, 2019 16:20
Show Gist options
  • Save pgbytes/2655704409622b01342db4cab2fe857d to your computer and use it in GitHub Desktop.
Save pgbytes/2655704409622b01342db4cab2fe857d to your computer and use it in GitHub Desktop.
bash-executor using github.com/go-cmd
package services
import (
"fmt"
"github.com/go-cmd/cmd"
"github.com/golang/glog"
"time"
)
type BashExecutor struct {
verbose bool
}
func NewBashExecutor(verbose bool) *BashExecutor {
return &BashExecutor{
verbose: verbose,
}
}
func (bs *BashExecutor) ExecuteCommand(commandString string) int {
// Disable output buffering, enable streaming
cmdOptions := cmd.Options{
Buffered: false,
Streaming: true,
}
mphCmd := cmd.NewCmdOptions(cmdOptions, "bash", "-c", commandString)
if bs.verbose {
glog.Infoln("Executing bash command: " + commandString)
}
// Print to STDOUT
if bs.verbose {
go func() {
for line := range mphCmd.Stdout {
fmt.Println(line)
}
}()
} else {
go func() {
for range mphCmd.Stdout {
// do nothing
}
}()
}
// Run the command
cmdStatus := <-mphCmd.Start()
// Cmd has finished but wait for goroutine to print all lines
for len(mphCmd.Stdout) > 0 {
time.Sleep(10 * time.Millisecond)
}
if cmdStatus.Exit != 0 {
glog.Errorf("Exit code: %d\n", cmdStatus.Exit)
glog.Errorf("Executed command: %s\n", commandString)
glog.Errorf("Error: %+v", cmdStatus.Error)
for _, line := range cmdStatus.Stderr {
fmt.Println(line)
}
return cmdStatus.Exit
}
glog.Infof("Command took %f seconds to complete", cmdStatus.Runtime)
return cmdStatus.Exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment