Go: strange results when using strings with exec.Command

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

Go: strange results when using strings with exec.Command

问题

我有一个处理Linux CLI命令及其参数的Go函数:

func cmd(cmd string, args ...string) ([]byte, error) {
    path, err := exec.Command("/usr/bin/which", cmd).Output()
    if err != nil {
        return []byte(""), err
    }
    response, err := exec.Command(string(path), args...).Output()
    if err != nil {
        response = []byte("Unknown")
    }
    return response, err
}

它被以下代码调用:

func main() {
    uname, err := cmd("uname", "-a")
    fmt.Println(string(uname))
}

"which"命令返回正确的二进制文件路径,但是当它尝试使用动态路径运行第二个exec命令时,返回的结果总是:

fork/exec /usr/bin/uname: no such file or directory
exit status 1

然而,如果第二个exec命令是硬编码的,一切都按预期工作并打印出uname的结果:

response, err := exec.Command("/usr/bin/uname", args...).Output()

我是否对exec和字符串的行为有所遗漏?

谢谢。

英文:

I have a Go function that processes Linux CLI commands and their arguments:

func cmd(cmd string, args ...string) ([]byte, error) {
	path, err := exec.Command("/usr/bin/which", cmd).Output()
	if err != nil {
		return []byte(""), err
	}
	response, err := exec.Command(string(path), args...).Output()
	if err != nil {
		response = []byte("Unknown")
	}
	return response, err
}

Which is called by the following:

func main() {
	uname, err := cmd("uname", "-a")
	fmt.Println(string(uname))
}

The "which" command returns the correct path to the binary but when it tries to run the second exec command with a dynamic path the return is always:

fork/exec /usr/bin/uname
: no such file or directory
exit status 1

Yet if the second exec command is hardcoded, everything works as expected and prints the uname:

response, err := exec.Command("/usr/bin/uname", args...).Output()

Am I missing something about how exec and strings behave?

Thanks

答案1

得分: 5

which命令在可执行文件的名称后打印一个换行符。path变量被设置为"/usr/bin/uname\n"。这个路径下没有可执行文件。额外的换行符在错误消息中可见(即在冒号之前的换行符)。

修剪换行符后,可以得到正确的可执行文件名称:

response, err := exec.Command(strings.TrimSuffix(string(path), "\n"), args...).Output()
英文:

The which command prints a newline following the name of the executable. The path variable is set to "/usr/bin/uname\n". There is no executable with this path. The extra newline is visible in the error message (the newline just before the ":").

Trim the newline suffix to get the correct name of the executable:

 response, err := exec.Command(strings.TrimSuffix(string(path), "\n"), args...).Output()

huangapple
  • 本文由 发表于 2014年9月10日 08:54:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/25755746.html
匿名

发表评论

匿名网友

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

确定