Go: strange results when using strings with exec.Command

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

Go: strange results when using strings with exec.Command

问题

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

  1. func cmd(cmd string, args ...string) ([]byte, error) {
  2. path, err := exec.Command("/usr/bin/which", cmd).Output()
  3. if err != nil {
  4. return []byte(""), err
  5. }
  6. response, err := exec.Command(string(path), args...).Output()
  7. if err != nil {
  8. response = []byte("Unknown")
  9. }
  10. return response, err
  11. }

它被以下代码调用:

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

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

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

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

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

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

谢谢。

英文:

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

  1. func cmd(cmd string, args ...string) ([]byte, error) {
  2. path, err := exec.Command("/usr/bin/which", cmd).Output()
  3. if err != nil {
  4. return []byte(""), err
  5. }
  6. response, err := exec.Command(string(path), args...).Output()
  7. if err != nil {
  8. response = []byte("Unknown")
  9. }
  10. return response, err
  11. }

Which is called by the following:

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

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:

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

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

  1. 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"。这个路径下没有可执行文件。额外的换行符在错误消息中可见(即在冒号之前的换行符)。

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

  1. 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:

  1. 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:

确定