使用exec.Command运行’find’命令。

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

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(&quot;find&quot;, &quot;/usr/bin&quot;, &quot;-maxdepth&quot;, 
        &quot;2&quot;, &quot;-iname&quot;, &quot;&#39;*go*&#39;&quot;, &quot;|&quot;, &quot;head&quot;, &quot;-10&quot;)
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(&quot;find&quot;, &quot;/usr/bin&quot;, &quot;-maxdepth&quot;, &quot;2&quot;, &quot;-iname&quot;, &quot;&#39;*go*&#39;&quot;)
out, err := cmd.CombinedOutput()
fmt.Println(err)
fmt.Println(string(out))

Output:

&lt;nil&gt;

答案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(&quot;head&quot;, &quot;args1&quot;, 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.

huangapple
  • 本文由 发表于 2015年6月30日 03:37:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/31124135.html
匿名

发表评论

匿名网友

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

确定