英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论