Go:执行shell命令

Vya*_*nov 1 bash exec go

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

  var command = pwd + "/build " + file_name

  dateCmd := exec.Command(string(command))
  dateOut, err := dateCmd.Output()
  check(err)
Run Code Online (Sandbox Code Playgroud)

如果command变量等于单个单词/home/slavik/project/build(构建是shell脚本),它可以工作,但是如果我尝试传递一些arg ie /home/slavik/project/build xxx或者/home/slavik/project/build -v=1Go程序引发异常,就像file /home/slavik/project/build not found

我的代码出了什么问题?

ear*_*arl 9

你必须分别传递程序和参数.查看exec.Command的签名:

func Command(name string, arg ...string) *Cmd
Run Code Online (Sandbox Code Playgroud)

所以如果你想通过例如-v=1,你的电话可能应该是这样的:

dateCmd := exec.Command(pwd + "/build", "-v=1")
Run Code Online (Sandbox Code Playgroud)