go语言exec.Command方法执行失败

时间:2012-07-24 02:22:41

标签: go

package main

import (
    "os/exec"
    "fmt"
)

func main(){
    cmd := exec.Command("find", "/home/d101270c/cbe", "-name","*.log", ">", "log.txt")
    fmt.Println(cmd)
    err := cmd.Run()
    if err != nil {
        fmt.Printf("%s\n", err)
        return
    }
}

运行结果:

<1067 linux20 [d101270c] :/home/d101270c>uname -a
Linux linux20 2.6.16.60-0.21-smp #1 SMP Tue May 6 12:41:02 UTC 2008 x86_64 x86_64 x86_64 GNU/Linux
<1068 linux20 [d101270c] :/home/d101270c>tgo
&{/usr/bin/find [find /home/d101270c/cbe -name *.log > log.txt] []  <nil> <nil> <nil> [] <nil> <nil> <nil> <nil> false [] [] [] [] <nil>}
exit status 1

此命令执行失败,并且不存在log.txt

为什么?

2 个答案:

答案 0 :(得分:3)

你传递了find个参数,比如`&gt;',它不明白,但shell确实如此。这对我有用:

(07:28) jnml@tsat:~/src/tmp/SO/11623232$ cat main.go 
package main

import (
    "fmt"
    "os"
    "os/exec"
)

func main() {
    //cmd := exec.Command("sh", "-c", "find /home/d101270c/cbe -name \\*.log > log.txt")
    cmd := exec.Command("sh", "-c", "find "+os.Getenv("HOME")+"/src -name \\*.go > go.txt")
    fmt.Println(cmd)
    err := cmd.Run()
    if err != nil {
        fmt.Printf("%s\n", err)
        return
    }
}
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ go build main.go 
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ ./main 
&{/bin/sh [sh -c find /home/jnml/src -name \*.go > go.txt] []  <nil> <nil> <nil> [] <nil> <nil> <nil> <nil> false [] [] [] [] <nil>}
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ ls -l
celkem 1408
-rw-r--r-- 1 jnml jnml    7845 2012-07-24 07:29 go.txt
-rwxr-xr-x 1 jnml jnml 1428319 2012-07-24 07:29 main
-rw-r--r-- 1 jnml jnml     332 2012-07-24 07:28 main.go
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ wc go.txt 
 131  131 7845 go.txt
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ tail go.txt 
/home/jnml/src/github.com/nsf/gocode/config.go
/home/jnml/src/github.com/nsf/gocode/rpc.go
/home/jnml/src/github.com/nsf/gocode/_gccgo/package.go
/home/jnml/src/github.com/nsf/gocode/_goremote/goremote.go
/home/jnml/src/github.com/nsf/gocode/scope.go
/home/jnml/src/github.com/nsf/gocode/formatters.go
/home/jnml/src/github.com/nsf/gocode/autocompletefile.go
/home/jnml/src/github.com/nsf/gocode/decl.go
/home/jnml/src/tmp/go/main.go
/home/jnml/src/tmp/SO/11623232/main.go
(07:29) jnml@tsat:~/src/tmp/SO/11623232$ 

答案 1 :(得分:1)

也许,你甚至不需要在这里使用shell。请参阅http://golang.org/pkg/os/exec/#Cmd.Output

亚历