1
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存在。

为什么?

4

2 回答 2

3

您正在传递find像 `>' 这样的参数,它不理解,但 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$ 
于 2012-07-24T05:34:03.827 回答
1

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

亚历克斯

于 2012-07-24T09:54:00.233 回答