让Go语言调用外部程序时支持管道符(3)

  靠,又不行了,提示:
  awk: 1: unexpected character '''
  awk: 1: unexpected character '''
  它不能支持参数中有引号的内容!

  怎么办,难道真的没辙了吗?老天不负有心人,终于被我找到解决办法了,而且更简单:

  package main
  
  import (
   "os"
   "os/exec"
  )
  
  func main() {
   run1()
   run2()
   run3()
   run4()
  }
  
  func run1() {
   cmd := exec.Command("ls", "|", "wc", "-l")
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr
   cmd.Start()
   cmd.Run()
   cmd.Wait()
  }
  
  func run2() {
   c1 := exec.Command("ls")
   c2 := exec.Command("wc", "-l")
   c2.Stdin, _ = c1.StdoutPipe()
   c2.Stdout = os.Stdout
   c2.Stderr = os.Stderr
   c2.Start()
   c1.Run()
   c2.Wait()
  }
  
  func run3() {
   c1 := exec.Command("ps", "-eaf")
   c2 := exec.Command("grep", `"nginx: master"`)
   c3 := exec.Command("grep", "-v", `"grep"`)
   c4 := exec.Command("awk", `'{print $2}'`)
   c2.Stdin, _ = c1.StdoutPipe()
   c3.Stdin, _ = c2.StdoutPipe()
   c4.Stdin, _ = c3.StdoutPipe()
  
   c4.Stdout = os.Stdout
   c4.Stderr = os.Stderr
  
   c4.Start()
   c3.Start()
   c2.Start()
   c1.Run()
   c4.Wait()
  }
  
  func run4() {
   cmd := exec.Command("/bin/sh", "-c", `ps -eaf|grep "nginx: master"|grep -v "grep"|awk '{print $2}'`)
   cmd.Stdout = os.Stdout
   cmd.Stderr = os.Stderr
   cmd.Start()
   cmd.Run()
   cmd.Wait()
  }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/e05b34768ecd37fbd563c20d0137b684.html