Golang 执行 shell 命令

  1. package main
  2. import (
  3. "fmt"
  4. "log"
  5. "os/exec"
  6. "strings"
  7. )
  8. func ExecShell(shellCmd string) []string {
  9. var rd []string
  10. cmd := exec.Command("bash", "-c", shellCmd)
  11. bytes, err := cmd.Output()
  12. if err != nil {
  13. fmt.Println("cmd.Output:", err)
  14. return rd
  15. }
  16. parts := strings.Split(strings.TrimSpace(string(bytes)), "\n")
  17. if len(parts) == 1 && parts[0] == "" {
  18. return rd
  19. }
  20. return parts
  21. }
  22. func main() {
  23. strA := ExecShell(`df -h`)
  24. log.Println("len", len(strA))
  25. for _, v := range strA {
  26. log.Println(v)
  27. }
  28. }

参考 https://blog.csdn.net/qq_36874881/article/details/78234005