Golang 执行 shell 命令
package main
import (
"fmt"
"log"
"os/exec"
"strings"
)
func ExecShell(shellCmd string) []string {
var rd []string
cmd := exec.Command("bash", "-c", shellCmd)
bytes, err := cmd.Output()
if err != nil {
fmt.Println("cmd.Output:", err)
return rd
}
parts := strings.Split(strings.TrimSpace(string(bytes)), "\n")
if len(parts) == 1 && parts[0] == "" {
return rd
}
return parts
}
func main() {
strA := ExecShell(`df -h`)
log.Println("len", len(strA))
for _, v := range strA {
log.Println(v)
}
}
参考 https://blog.csdn.net/qq_36874881/article/details/78234005