os.Exec和/ bin / sh:执行多个命令

时间:2015-02-01 21:58:51

标签: bash shell go sh

我遇到了os/exec库的问题。我想运行一个shell并传递多个命令来运行,但是当我这样做时它会失败。这是我的测试代码:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    fmt.Printf("-- Test 1 --\n`")
    command1 := fmt.Sprintf("\"%s\"", "pwd") // this one succeeds
    fmt.Printf("Running: %s\n", command1)
    cmd1 := exec.Command("/bin/sh", "-c", command1)
    output1,err1 := cmd1.CombinedOutput()
    if err1 != nil {
        fmt.Printf("error: %v\n", err1)
        return
    }
    fmt.Printf(string(output1))


    fmt.Printf("-- Test 2 --\n")
    command2 := fmt.Sprintf("\"%s\"", "pwd && pwd") // this one fails
    fmt.Printf("Running: %s\n", command2)
    cmd2 := exec.Command("/bin/sh", "-c", command2)
    output2,err2 := cmd2.CombinedOutput()
    if err2 != nil {
        fmt.Printf("error: %v\n", err2)
        return
    }
    fmt.Printf(string(output2))
}

运行此操作时,我在第二个示例中收到错误127。看起来它正在寻找一个文字" pwd&& PWD"命令而不是将其评估为脚本。

如果我从命令行执行相同的操作,它就可以正常工作。

$ /bin/sh -c "pwd && pwd"

我在OS X 10.10.2上使用Go 1.4。

1 个答案:

答案 0 :(得分:2)

引号适用于您键入命令行的shell,在以编程方式启动应用程序时不应包含它们

只需进行此更改即可运行:

command2 := "pwd && pwd" // you don't want the extra quotes
相关问题