英文:
Run 'find' using exec.Command
问题
我正在尝试使用exec.Command
运行find
命令:
cmd := exec.Command("find", "/usr/bin", "-maxdepth", "2", "-iname", "'*go*'", "|", "head", "-10")
out, err := cmd.CombinedOutput()
fmt.Println(err)
fmt.Println(string(out))
不幸的是,这会导致以下输出:
exit status 1
find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
我在这里漏掉了什么?
编辑:
即使我尝试不使用管道,它仍然失败:
cmd := exec.Command("find", "/usr/bin", "-maxdepth", "2", "-iname", "'*go*'")
out, err := cmd.CombinedOutput()
fmt.Println(err)
fmt.Println(string(out))
输出:
<nil>
英文:
I am trying to run the find
command using exec.Command
:
cmd := exec.Command("find", "/usr/bin", "-maxdepth",
"2", "-iname", "'*go*'", "|", "head", "-10")
out, err := cmd.CombinedOutput()
fmt.Println(err)
fmt.Println(string(out))
Unfortunately this fails with the following output:
exit status 1
find: paths must precede expression: |
Usage: find [-H] [-L] [-P] [-Olevel] [-D help|tree|search|stat|rates|opt|exec] [path...] [expression]
What am I missing here?
EDIT:
Even if I try it without piping this still fails:
cmd := exec.Command("find", "/usr/bin", "-maxdepth", "2", "-iname", "'*go*'")
out, err := cmd.CombinedOutput()
fmt.Println(err)
fmt.Println(string(out))
Output:
<nil>
答案1
得分: 3
你正在使用|
符号,它将前一个命令的输出传递给下一个命令。相反,你可能需要在Go中使用两个命令。将string(out)
作为第二个命令的输入,而不是尝试使用管道符号并将两个bash命令组合成一个Go命令。
// 这是伪代码
cmd2 := exec.Command("head", "args1", string(out))
基本上,你需要自己处理管道操作,并使用两个单独的命令,而不是尝试使用管道符号来组合命令。
英文:
You're using |
which pipes the output of the previous command into the next. Instead you probably need two commands in Go. Use string(out)
as input to the second one rather than trying to pipe it and compose the two bash commands into one Go command.
// this is pseudo code
cmd2 := exec.Command("head", "args1", string(out))
Basically, you have to do the piping yourself and use two separate commands rather than trying to invoke command once with commands that are composed using pipe.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论