-
Notifications
You must be signed in to change notification settings - Fork 0
/
commandutils.go
69 lines (57 loc) · 1.12 KB
/
commandutils.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package go_utils
import (
"bytes"
"fmt"
"os/exec"
"strings"
"github.com/kballard/go-shellquote"
)
func ExecuteCommand(command string, doWait bool) int {
words, err := shellquote.Split(command)
if err != nil {
// TODO: handle this
return -1
}
var cmd *exec.Cmd
if len(words) == 1 {
cmd = exec.Command(command)
} else {
cmd = exec.Command(words[0], words[1:]...)
}
cmd.Stdout = nil
cmd.Stderr = nil
err = cmd.Start()
if err != nil {
fmt.Println(err)
}
pid := cmd.Process.Pid
if doWait {
cmd.Wait()
}
return pid
}
func ExecuteCommandAndGetResults(command string) (string, error) {
words, err := shellquote.Split(command)
if err != nil {
// TODO: handle this better
return "", err
}
var cmd *exec.Cmd
if len(words) == 1 {
cmd = exec.Command(command)
} else {
cmd = exec.Command(words[0], words[1:]...)
}
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
return "", err
}
error_s := string(stderr.Bytes())
if len(error_s) > 0 {
fmt.Printf("ERROR: %s", error_s)
}
return strings.Trim(string(stdout.Bytes()), "\n"), err
}