You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
ntool/internal/common/cli.go

71 lines
1.3 KiB
Go

package common
import (
"os"
"os/exec"
"path/filepath"
"strings"
)
// 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
}
// curShell cache
var curShell string
// CurrentShell get current used shell env file.
//
// eg "/bin/zsh" "/bin/bash".
// if onlyName=true, will return "zsh", "bash"
func CurrentShell(onlyName bool) (binPath string) {
var err error
if curShell == "" {
binPath = os.Getenv("SHELL")
if len(binPath) == 0 {
binPath, err = ShellExec("echo $SHELL")
if err != nil {
return ""
}
}
binPath = strings.TrimSpace(binPath)
// cache result
curShell = binPath
} else {
binPath = curShell
}
if onlyName && len(binPath) > 0 {
binPath = filepath.Base(binPath)
}
return
}
// HasShellEnv has shell env check.
//
// Usage:
//
// HasShellEnv("sh")
// HasShellEnv("bash")
func HasShellEnv(shell string) bool {
// can also use: "echo $0"
out, err := ShellExec("echo OK", shell)
if err != nil {
return false
}
return strings.TrimSpace(out) == "OK"
}