如何执行shell命令

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

How to execute shell command

问题

我在Go程序中执行shell命令时遇到了一些问题:

  var command = pwd + "/build " + file_name

  dateCmd := exec.Command(string(command))
  dateOut, err := dateCmd.Output()
  check(err)

如果command变量等于一个单词,比如/home/slavik/project/build(build是shell脚本),它可以正常工作,但是如果我尝试传递一些参数,比如/home/slavik/project/build xxx或者/home/slavik/project/build -v=1,Go程序会抛出一个异常,类似于file /home/slavik/project/build not found

我的代码有什么问题?

英文:

I have some trouble with execute shell commands from a Go program:

  var command = pwd + "/build " + file_name

  dateCmd := exec.Command(string(command))
  dateOut, err := dateCmd.Output()
  check(err)

If command variable equals a single word like /home/slavik/project/build (build is shell script) it works, but if I try to pass some arg i.e. /home/slavik/project/build xxx or /home/slavik/project/build -v=1 the Go program raises an exception like file /home/slavik/project/build not found

What's wrong with my code?

答案1

得分: 9

你必须分别传递程序和参数。请参考exec.Command的签名:

func Command(name string, arg ...string) *Cmd

所以如果你想传递例如-v=1,你的调用可能应该类似于:

dateCmd := exec.Command(pwd + "/build", "-v=1")
英文:

You have to pass the program and the arguments separately. See the signature of exec.Command:

func Command(name string, arg ...string) *Cmd

So if you want to pass e.g. -v=1, your call probably should look something like:

dateCmd := exec.Command(pwd + "/build", "-v=1")

答案2

得分: 4

使用

exec.Command(pwd + "/build", fileName)
英文:

Use

exec.Command(pwd + "/build", fileName)

huangapple
  • 本文由 发表于 2013年6月9日 19:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/17009039.html
匿名

发表评论

匿名网友

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

确定