Go 运行';查找';使用exec.Command
我正在尝试使用Go 运行';查找';使用exec.Command,go,Go,我正在尝试使用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
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>
您正在使用
|
将上一个命令的输出传输到下一个命令。相反,在Go中可能需要两个命令。使用string(out)
作为第二个命令的输入,而不是尝试通过管道将两个bash命令组合成一个Go命令
// this is pseudo code
cmd2 := exec.Command("head", "args1", string(out))
基本上,您必须自己进行管道处理,并使用两个单独的命令,而不是尝试使用管道组成的命令调用一次命令。a
|
pipe是一个shell构造。您不能在命令中使用它。如果在*go*
周围有不必要的单引号,请删除它们。