如何在go中执行带有反斜杠的命令

How to execute a command with backslashes in go

我想 return 使用 go

的应用程序版本的输出

为什么下面会失败?

emulatorCmd := exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/Bot\`, `Framework\`, `Emulator.app`)
emulatorVersion, err := emulatorCmd.Output()
if err != nil {                      
   log.Fatalf("cmd.Run() failed in emulator", err)                       
   fmt.Println("Looks like you don't have the Bot Emulator installed yet, download here: https://github.com/Microsoft/BotFramework-Emulator/releases/tag/v4.5.2")
} else {
   fmt.Println("Emulator:", string(emulatorVersion))

}

给予:

cmd.Run() failed in emulator%!(EXTRA *exec.ExitError=exit status 1)

但是当我用名称中没有空格(因此不需要反斜杠)的应用程序替换命令时,例如

exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/FaceTime.app`)

成功,给出:

Emulator: kMDItemVersion = "5.0"

我试着把它们都放在一个字符串中,但是命令中的空格需要用逗号分隔。还尝试使用两个“\”反斜杠,现在即使使用反引号也不起作用。

还查看了 go string literals 页面,但没有找到与此问题相关的内容: https://golang.org/ref/spec#raw_string_lit

您在命令行中需要的反斜杠用于转义空格,以防止它们被 shell 视为参数分隔符 。由于在 Go 中没有 shell 涉及以这种方式执行,因此您不需要它们。您可以:

exec.Command(`mdls`, `-name`, `kMDItemVersion`, `/Applications/Bot Framework Emulator.app`)