【问题标题】:Why do some commands return output but not others for exec.Command()为什么有些命令返回输出而其他命令不返回 exec.Command()
【发布时间】:2019-01-09 22:59:51
【问题描述】:

我试图弄清楚为什么某些 shell 命令可以与 goloang exec.Command 一起使用,而其他命令在终端输入时都返回相同的结果时不能。我基本上想对 windows 和 mac 二进制文件使用相同的命令 (exec.Command("where", "go").Output())。

这些具体:

goInstalled, err := exec.Command("where", "go").Output() // does not return output on mac when compiled but does in terminal command. DOES return output on windows compiled.

goInstalled, err := exec.Command("which", "go").Output() // does not return output on mac when compiled but does in terminal command

goInstalled, err := exec.Command("command", "-v", "go").Output() // returns output when compiled and as terminal command (mac only)

如果可能,我想对 windows 和 mac (darwin) 使用相同的命令,而不是创建两个单独的函数来检查用户机器上是否安装了东西。

【问题讨论】:

  • 你一定忽略了err。
  • “无输出”我的意思是它确实触发了 err != nil 块,并且这些 goInstalled 的值为 []。 goInstalled, err := exec.Command("command", "-v", "go").Output() 不会触发 err != nil 块并返回输出 [字节数]
  • exec.Command 不 执行 shell 命令。它执行作为第一个参数给出的程序。如果不显式执行 shell,Shell 内置函数将无法工作。在这种情况下,您可以简单地调用exec.LookPath。

标签: go cmd darwin


【解决方案1】:

您在这里遇到的主要问题是exec.Command 执行程序,而您尝试使用的命令实际上是内置的。

要使用内置函数,您需要使用 exec.LookPath 找到它们,并且它们通常不能在 shell 之外使用。

如果必须,您也可以从 在 shell 中执行命令,方法是将 shell 作为第一个参数:

exec.Command("/bin/bash", "-c", "command -v foo")

【讨论】:

  • 无需自己调用 LookPath:“如果 name 不包含路径分隔符,Command 使用 LookPath 将 name 解析为完整路径”golang.org/pkg/os/exec/#Command
  • 我的错误,我会更新我的评论。谢谢你的收获!
猜你喜欢
  • 1970-01-01
  • 2011-12-11
  • 2013-02-19
  • 1970-01-01
  • 2018-12-04
  • 2013-01-28
  • 2012-05-11
  • 2019-03-17
  • 1970-01-01
相关资源
最近更新 更多