我试图调用内建函数find以打印出子文件夹my-files中所有文本文件的内容。我知道可以使用更简单的方法来执行此操作,但是我需要使其与exec一起使用。我怀疑exec无法正确处理报价。我的初始代码如下:
fullCmd := "find my-files -maxdepth 1 -type f"
cmdParts := strings.Split(fullCmd, " ")
output, _ := exec.Command(cmdParts[0], cmdParts[1:]...).CombinedOutput()
fmt.Println("Output is...")
fmt.Println(string(output))
Run Code Online (Sandbox Code Playgroud)
这可以正常工作并打印出来
Output is...
my-files/goodbye.txt
my-files/badfile.java
my-files/hello.txt
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试开始添加“奇怪”字符时,它会崩溃。如果我将第一行更改为
fullCmd := "find my-files -maxdepth 1 -type f -iname \"*.txt\""
Run Code Online (Sandbox Code Playgroud)
什么都没打印出来。更糟糕的是,如果我将行更改为:
fullCmd := "find my-files -maxdepth 1 -type f -exec cat {} \\;"
Run Code Online (Sandbox Code Playgroud)
使用此标准输出查找错误:
Output is...
find: -exec: no terminating ";" or "+"
Run Code Online (Sandbox Code Playgroud)
我以为我正确地逃避了必要的角色,但我想不是。关于如何使命令起作用的任何想法?作为参考,当直接在命令行上输入此命令时,它确实满足我的要求:
find my-files -maxdepth 1 -type f -iname "*.txt" -exec cat {} \;
Run Code Online (Sandbox Code Playgroud)
它与“怪异”字符无关。\"*.txt\""为shell引用了,但是您没有在shell中运行它。它应该是*.txt,这是您要find作为以下值接收的实际参数-iname:
fullCmd := "find my-files -maxdepth 1 -type f -iname *.txt"
Run Code Online (Sandbox Code Playgroud)
但是,由于这不是外壳程序,因此强烈建议不要将类似外壳程序的命令构建为单个字符串并在空格上分割;只是首先将args作为数组提供,以免引起混淆。