-
Notifications
You must be signed in to change notification settings - Fork 191
/
Copy pathexec.go
87 lines (73 loc) · 2.13 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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package sysutil
import (
"os/exec"
"github.com/gookit/goutil/cliutil/cmdline"
"github.com/gookit/goutil/internal/checkfn"
"github.com/gookit/goutil/sysutil/cmdr"
)
// NewCmd instance
func NewCmd(bin string, args ...string) *cmdr.Cmd {
return cmdr.NewCmd(bin, args...)
}
// FlushExec command, will flush output to stdout,stderr
func FlushExec(bin string, args ...string) error {
return cmdr.NewCmd(bin, args...).FlushRun()
}
// QuickExec quick exec a simple command line, return combined output.
func QuickExec(cmdLine string, workDir ...string) (string, error) {
return ExecLine(cmdLine, workDir...)
}
// ExecLine quick exec a command line string, return combined output.
//
// NOTE: not support | or ; in cmdLine
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.CombinedOutput()
return string(bs), err
}
// ExecCmd a command and return combined 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.CombinedOutput()
return string(bs), err
}
// ShellExec exec command by shell cmdLine, return combined output.
//
// shells e.g. "/bin/sh", "bash", "cmd", "cmd.exe", "powershell", "powershell.exe", "pwsh", "pwsh.exe"
//
// eg: ShellExec("ls -al")
func ShellExec(cmdLine string, shells ...string) (string, error) {
// shell := "/bin/sh"
shell := "sh"
if len(shells) > 0 {
shell = shells[0]
}
// "-c" for bash,sh,zsh shell
mark := "-c"
// special for Windows shell
if IsWindows() {
// use cmd.exe, mark is "/c"
if checkfn.StringsContains([]string{"cmd", "cmd.exe"}, shell) {
mark = "/c"
} else if checkfn.StringsContains([]string{"powershell", "powershell.exe", "pwsh", "pwsh.exe"}, shell) {
// "-Command" for powershell
mark = "-Command"
}
}
cmd := exec.Command(shell, mark, cmdLine)
bs, err := cmd.CombinedOutput()
return string(bs), err
}