首页 > 解决方案 > 如何在go中执行带有反斜杠的命令

问题描述

我想使用 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

标签: gooutputexec

解决方案


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

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

推荐阅读