-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add shell helpers to cmder package
- Loading branch information
Showing
2 changed files
with
61 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package cmder | ||
|
||
import ( | ||
"fmt" | ||
"strings" | ||
"time" | ||
) | ||
|
||
var ( | ||
// DefaultShellTimeout Shell 执行默认超时时间 | ||
DefaultShellTimeout = 10 * time.Second | ||
|
||
// BashCmd 主命令绝对路径 | ||
BashCmd = []string{"/bin/bash"} | ||
) | ||
|
||
// RunShell 运行 Shell 脚本返回是否执行成功 | ||
func RunShell(sh string, args ...string) (ok bool) { | ||
_, _, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...) | ||
return | ||
} | ||
|
||
// RunShellTimeout 运行 Shell 脚本返回是否执行成功 | ||
func RunShellTimeout(sh string, timeout time.Duration, args ...string) (ok bool) { | ||
_, _, ok = RunShellTimeoutWithResult(sh, timeout, args...) | ||
return | ||
} | ||
|
||
// RunShellWithResult 运行 Shell 脚本并返回输出结果 | ||
func RunShellWithResult(sh string, args ...string) (stdout, errout string, ok bool) { | ||
stdout, errout, ok = RunShellTimeoutWithResult(sh, DefaultShellTimeout, args...) | ||
return | ||
} | ||
|
||
// RunShellTimeoutWithResult 运行 Shell 脚本并返回标准输出和错误输出, 以及是否执行成功 | ||
// 示例命令: /bin/bash /opt/app/script/echo.sh my-app | ||
// 示例调用: RunShellTimeoutWithResult("/opt/app/script/echo.sh", 3*time.Second, []string{"my-app"}) | ||
func RunShellTimeoutWithResult(sh string, timeout time.Duration, args ...string) (stdout, errout string, ok bool) { | ||
cmd := append(BashCmd, sh) | ||
if len(args) > 0 { | ||
cmd = append(cmd, args...) | ||
} | ||
|
||
status := RunCmd(cmd, timeout) | ||
stdout = strings.Join(status.Stdout, "\n") | ||
stdout = strings.TrimSpace(stdout) | ||
errout = "" | ||
if status.Error != nil { | ||
errout += fmt.Sprintf("error: %v\n", status.Error) | ||
} | ||
errout += strings.Join(status.Stderr, "\n") | ||
errout = strings.TrimSpace(errout) | ||
ok = status.Exit == 0 && status.Error == nil | ||
return | ||
} |