Bash os.Exec和/bin/sh:执行多个命令
我遇到了Bash os.Exec和/bin/sh:执行多个命令,bash,shell,go,sh,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("Runnin
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。引号用于您键入命令行的shell,在以编程方式启动应用程序时不应包括引号 只要进行此更改,它就会起作用:
command2 := "pwd && pwd" // you don't want the extra quotes