|
| 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