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

huangapple go评论82阅读模式
英文:

os.Exec and /bin/sh: executing multiple commands

问题

我遇到了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"

我正在使用Go 1.4和OS X 10.10.2。

英文:

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 --\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))
}

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

得分: 2

引号是用于您在命令行中输入命令的外壳,当以编程方式启动应用程序时,不应包含在内。

只需进行以下更改,它就会正常工作:

command2 := "pwd && pwd" // 您不需要额外的引号
英文:

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

huangapple
  • 本文由 发表于 2015年2月2日 05:58:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/28268433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定