duanbishai5271 2012-07-24 02:22
浏览 735
已采纳

Go语言的exec.Command方法执行失败

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
", err)
        return
    }
}

Run result:

<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

This command execute failed, and no log.txt exists.

Why?

  • 写回答

2条回答 默认 最新

  • douguanya4248 2012-07-24 05:34
    关注

    You're passing find arguments like `>', which it doesn't understand, but the shell does. This works for me:

    (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
    ", 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条)

报告相同问题?