dongwusang0314 2015-02-01 21:58
浏览 300
已采纳

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

I've run into an issue with the os/exec library. I want to run a shell and pass it multiple commands to run, but it's failing when I do. Here's my test code:

package main

import (
    "fmt"
    "os/exec"
)

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


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

When running this I get an error 127 on the second example. It seems like it's looking for a literal "pwd && pwd" command instead of evaluating it as a script.

If I do the same thing from the command line it works just fine.

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

I'm using Go 1.4 on OS X 10.10.2.

  • 写回答

1条回答 默认 最新

  • douqiang7976 2015-02-01 22:29
    关注

    the quotes are for your shell where you typed the command line, they should not be included when programatically launching an app

    just make this change and it will work:

    command2 := "pwd && pwd" // you don't want the extra quotes
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗