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

时间:2019-07-24 13:23:37

标签: go output exec

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

我尝试将所有内容放在一个字符串中,但是命令中的空格需要用逗号分隔。还尝试使用两个'\'反斜杠,现在即使使用反斜杠也不起作用。

还查看了转到字符串文字页面,但未找到与此问题相关的内容: https://golang.org/ref/spec#raw_string_lit

1 个答案:

答案 0 :(得分:1)

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

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