英文:
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\"")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论