Skip to content

Commit d4f64f0

Browse files
committed
chore: add shell helpers to cmder package
1 parent 1ca8a12 commit d4f64f0

2 files changed

Lines changed: 61 additions & 4 deletions

File tree

cmder/helper.go renamed to cmder/cmder.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,12 @@ import (
1111
"github.com/go-cmd/cmd"
1212
)
1313

14-
// 命令执行超时时间默认值
15-
const cmdTimeout = 3 * time.Second
14+
var (
15+
// DefaultCMDTimeout 命令执行超时时间默认值
16+
DefaultCMDTimeout = 3 * time.Second
1617

17-
var ErrCMDTimeout = errors.New("command execution timed out")
18+
ErrCMDTimeout = errors.New("command execution timed out")
19+
)
1820

1921
// RunCmd 运行命令, 返回结果和状态
2022
func RunCmd(cmdArgs []string, timeout ...time.Duration) cmd.Status {
@@ -29,7 +31,7 @@ func RunCmdCombinedOutput(cmdArgs []string, timeout ...time.Duration) cmd.Status
2931
}
3032

3133
func RunCmdWithOptions(cmdArgs []string, opts cmd.Options, timeout ...time.Duration) cmd.Status {
32-
dur := cmdTimeout
34+
dur := DefaultCMDTimeout
3335
if len(timeout) > 0 {
3436
dur = timeout[0]
3537
}

cmder/shell.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package cmder
2+
3+
import (
4+
"fmt"
5+
"strings"
6+
"time"
7+
)
8+
9+
var (
10+
// DefaultShellTimeout Shell 执行默认超时时间
11+
DefaultShellTimeout = 10 * time.Second
12+
13+
// BashCmd 主命令绝对路径
14+
BashCmd = []string{"/bin/bash"}
15+
)
16+
17+
// RunShell 运行 Shell 脚本返回是否执行成功
18+
func RunShell(sh string, args ...string) (ok bool) {
19+
_, _, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...)
20+
return
21+
}
22+
23+
// RunShellTimeout 运行 Shell 脚本返回是否执行成功
24+
func RunShellTimeout(sh string, timeout time.Duration, args ...string) (ok bool) {
25+
_, _, ok = RunShellTimeoutWithResult(sh, timeout, args...)
26+
return
27+
}
28+
29+
// RunShellWithResult 运行 Shell 脚本并返回输出结果
30+
func RunShellWithResult(sh string, args ...string) (stdout, errout string, ok bool) {
31+
stdout, errout, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...)
32+
return
33+
}
34+
35+
// RunShellTimeoutWithResult 运行 Shell 脚本并返回标准输出和错误输出, 以及是否执行成功
36+
// 示例命令: /bin/bash /opt/app/script/echo.sh my-app
37+
// 示例调用: RunShellTimeoutWithResult("/opt/app/script/echo.sh", 3*time.Second, "my-app")
38+
func RunShellTimeoutWithResult(sh string, timeout time.Duration, args ...string) (stdout, errout string, ok bool) {
39+
cmd := append(BashCmd, sh)
40+
if len(args) > 0 {
41+
cmd = append(cmd, args...)
42+
}
43+
44+
status := RunCmd(cmd, timeout)
45+
stdout = strings.Join(status.Stdout, "\n")
46+
stdout = strings.TrimSpace(stdout)
47+
errout = ""
48+
if status.Error != nil {
49+
errout += fmt.Sprintf("error: %v\n", status.Error)
50+
}
51+
errout += strings.Join(status.Stderr, "\n")
52+
errout = strings.TrimSpace(errout)
53+
ok = status.Exit == 0 && status.Error == nil
54+
return
55+
}

0 commit comments

Comments
 (0)