当前位置:   article > 正文

Go执行shell命令_go shell

go shell
  1. func main() {
  2. cmd := exec.Command("ls", "-lah")
  3. out, err := cmd.CombinedOutput()
  4. if err != nil {
  5. log.Fatalf("cmd.Run() failed with %s\n", err)
  6. }
  7. fmt.Printf("combined out:\n%s\n", string(out))
  8. //比如我现在有个定时任务需要执行,封装一个方法自动执行
  9. cmdStr := "cd /go/leyangjun/test/ && ./main crontab --run=single --job=myCrontabName"
  10. runCmd := exec.Command("/bin/bash", "-c", cmdStr)
  11. runCmdOut, err := runCmd.CombinedOutput()
  12. if err != nil {
  13. fmt.Println("命令执行失败")
  14. }else{
  15. fmt.Println("命令执行成功")
  16. }
  17. }
  18. //检查命令是否存在
  19. func checkExists() {
  20. path, err := exec.LookPath("pwd")
  21. if err != nil {
  22. fmt.Printf("pwd不存在\n")
  23. } else {
  24. fmt.Printf("'pwd' executable is in '%s'\n", path)
  25. }
  26. }
  27. //两个命令依次执行
  28. func successivelyExists() {
  29. c1 := exec.Command("ls")
  30. c2 := exec.Command("wc", "-l")
  31. c2.Stdin, _ = c1.StdoutPipe()
  32. c2.Stdout = os.Stdout
  33. _ = c2.Start()
  34. _ = c1.Run()
  35. _ = c2.Wait()
  36. }
  37. //按行读取输出的内容
  38. func readByRowExists() {
  39. cmd := exec.Command("ls", "-h")
  40. stdout, _ := cmd.StdoutPipe()
  41. cmd.Start()
  42. reader := bufio.NewReader(stdout)
  43. for {
  44. line, err := reader.ReadString('\n')
  45. line = strings.TrimSpace(line)
  46. if err != nil || io.EOF == err {
  47. break
  48. }
  49. log.Println(line)
  50. }
  51. cmd.Wait()
  52. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/650623
推荐阅读
相关标签
  

闽ICP备14008679号