Go语言中的shell执行
package main
import (
"fmt"
"os"
"os/exec"
"strings"
)
func getstatusoutput(args ...string) (status int, output string) {
exec_command := exec.Command(args[0], args[1:]...)
std_out, std_err := exec_command.Output()
status = exec_command.ProcessState.ExitCode()
if std_err != nil {
output = std_err.Error()
} else {
output = string(std_out)
}
return
}
func main() {
// command := []string{"echo", "-n", "HelloWorld"}
command_line := "echo -n HelloWorld"
command := strings.Fields(command_line)
shell := os.Getenv("SHELL")
status, output := getstatusoutput(command...)
fmt.Printf("--- Result ---------------\n")
fmt.Printf("Shell : %s\n", shell)
fmt.Printf("Command : %s\n", command)
fmt.Printf("StatusCode : %d\n", status)
fmt.Printf("ResultMessage: %s\n", output)
fmt.Printf("--------------------------\n")
}
结果
--- Result ---------------
Shell : /bin/bash
Command : [echo -n HelloWorld]
StatusCode : 0
ResultMessage: HelloWorld
--------------------------
故意让其失败 (gu yi rang qi shi bai)
--- Result ---------------
Shell : /bin/bash
Command : [echa -n HelloWorld]
StatusCode : -1
ResultMessage: exec: "echa": executable file not found in $PATH
--------------------------
请参照以下内容。
包 exec
https://golang.org/pkg/os/exec/
如何在Go中执行命令并获取退出代码的方法
https://qiita.com/hnakamur/items/5e6f22bda8334e190f63
在Golang中,如何将错误转换为字符串?(https://www.systutorials.com/in-golang-how-to-convert-an-error-to-a-string/)