在使用Golang运行Grep命令时出现退出状态2。

huangapple go评论67阅读模式
英文:

Exit Status 2 on running Grep command using Golang

问题

我使用Golang编写了一个简单的脚本来使用一些参数来grep一个日志文件。这是我的shell命令:

grep CRON var/log/sys | tail -5 | grep "cd /home/raka/repo && git status"

我想使用os/exec包在Golang中运行上述命令。这是我的代码片段:

var (
  reader io.Reader
  out    []byte
  err    error
  commandName string = "grep"
)

args := []string{"CRON", "/var/log/syslog", "| tail -6", "| grep \"git status\""}

cmd := exec.Command(commandName, args...)
r, err = cmd.StdoutPipe()
err = cmd.Start()
out, err = ioutil.ReadAll(r)
err = cmd.Wait()

return strings.Split(string(out), "\n")

目前,上面的代码片段不起作用,因为出现了exit status 2的错误。你们有没有解决这个问题的办法?非常感谢。

英文:

I write simple script using Golang to grep a log file with some parameters. Here's my shell command

grep CRON var/log/sys | tail -5 | grep "cd /home/raka/repo && git status"

I want to run command above in Golang using os/exec package. Here's my code sniped.

var (
  reader io.Reader
  out    []byte
  err    error
  commandName string = "grep"
)

args := []string{"CRON", "/var/log/syslog", "| tail -6", "| grep \"git status\""}

cmd := exec.Command(commandName, args...)
r, err = cmd.StdoutPipe()
err = cmd.Start()
out, err = ioutil.ReadAll(r)
err = cmd.Wait()

return strings.Split(string(out), "\n")```

Currently, the sniped above doesn't work, because of exit status 2.
Any of you guys/ladies have solution for this problem? thank you so much.

答案1

得分: 8

管道(|)是由一个shell程序(如bash)实现的。如果你想使用它们,你应该执行一个包含管道程序调用的shell命令:

exec.Command("/bin/sh", "-c",
    "grep CRON var/log/sys | tail -5 | grep \"cd /home/raka/repo && git status\"")
英文:

Pipes (|) are implemented by a shell program (like bash). If you want to use them you should execute shell passing a command containing piped program invocations:

exec.Command("/bin/sh", "-c",
	"grep CRON var/log/sys | tail -5 | grep \"cd /home/raka/repo && git status\"")

huangapple
  • 本文由 发表于 2016年1月8日 12:34:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/34669561.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定