forked from gookit/goutil
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexec.go
72 lines (59 loc) · 1.5 KB
/
exec.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
70
71
72
package sysutil
import (
"bytes"
"os/exec"
"github.com/gookit/goutil/cliutil/cmdline"
"github.com/gookit/goutil/sysutil/cmdr"
)
// NewCmd instance
func NewCmd(bin string, args ...string) *cmdr.Cmd {
return cmdr.NewCmd(bin, args...)
}
// FlushExec instance
func FlushExec(bin string, args ...string) error {
return cmdr.NewCmd(bin, args...).FlushRun()
}
// QuickExec quick exec an simple command line
func QuickExec(cmdLine string, workDir ...string) (string, error) {
return ExecLine(cmdLine, workDir...)
}
// ExecLine quick exec an command line string
func ExecLine(cmdLine string, workDir ...string) (string, error) {
p := cmdline.NewParser(cmdLine)
// create a new Cmd instance
cmd := p.NewExecCmd()
if len(workDir) > 0 {
cmd.Dir = workDir[0]
}
bs, err := cmd.Output()
return string(bs), err
}
// ExecCmd a command and return output.
//
// Usage:
//
// ExecCmd("ls", []string{"-al"})
func ExecCmd(binName string, args []string, workDir ...string) (string, error) {
// create a new Cmd instance
cmd := exec.Command(binName, args...)
if len(workDir) > 0 {
cmd.Dir = workDir[0]
}
bs, err := cmd.Output()
return string(bs), err
}
// ShellExec exec command by shell cmdLine. eg: "ls -al"
func ShellExec(cmdLine string, shells ...string) (string, error) {
// shell := "/bin/sh"
shell := "sh"
if len(shells) > 0 {
shell = shells[0]
}
var out bytes.Buffer
cmd := exec.Command(shell, "-c", cmdLine)
cmd.Stdout = &out
if err := cmd.Run(); err != nil {
return "", err
}
return out.String(), nil
}