Golag执行命令和Bash问题

时间:2019-01-11 20:30:20

标签: go

我有一个示例go程序,该程序未执行特定类型的语法。直接在bash上执行时,相同的命令字符串也可以正常工作。可能是GoLang方法添加了引号或我无法弄清楚的内容。这是示例程序

func main() {
    cmd:= "/usr/bin/vmtoolsd --cmd 'info-get guestinfo.ovfEnv'"
    //cmd:= "/usr/bin/vmtoolsd --help"
    words := strings.Fields(cmd)
    fmt.Printf("\nwords are : %v\n",words)
    oscmd := &exec.Cmd{
        Path: words[0],
        Args: words[:],
    }
    stdoutStderr, err:=oscmd.CombinedOutput()
    fmt.Printf("err:%v\n",err)
    fmt.Printf("output:\n%v\n",string(stdoutStderr))

    fmt.Printf("execute again")
    cmd2:="/usr/bin/vmtoolsd"
    arg:="--cmd \"info-get guestinfo.ovfEnv\""
    output:=exec.Command(cmd2,arg).Run()
    if output!=nil {
        fmt.Printf("\nsome error\n")
    }
    if output!=nil {
        fmt.Println(os.Stderr,output.Error())
    }
    //fmt.Printf("%v",cmd)
}

程序输出

[root @ localhost tmp]#./main

words are : [/usr/bin/vmtoolsd --cmd 'info-get guestinfo.ovfEnv']
err:exit status 1
output:
Unknown command

execute again
some error
&{0xc000052120} exit status 1

请注意,如果我只是将命令更改为/usr/bin/vmtoolsd --help,它就可以工作。我敢肯定,这与外壳在故障情况下解释参数的方式有关。任何提示将不胜感激。

0 个答案:

没有答案