I'm trying to call the builtin function find
to print out the contents of all the text files in a subfolder my-files. I understand that there are easier ways to do this, but I need to get it working with exec. I suspect that exec is not handling quotes correctly. My initial code is as follows:
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))
This works fine and prints out
Output is...
my-files/goodbye.txt
my-files/badfile.java
my-files/hello.txt
However, when I then try to start adding 'weirder' characters, it falls apart. If I change the first line to
fullCmd := "find my-files -maxdepth 1 -type f -iname \"*.txt\""
Nothing prints out. Worse, if I change the line to:
fullCmd := "find my-files -maxdepth 1 -type f -exec cat {} \\;"
Find errors out with this stdout:
Output is...
find: -exec: no terminating ";" or "+"
I thought I was correctly escaping the neccesary characters, but I guess not. Any ideas on how to get the command to work? For reference, this command does exactly what I want when entered directly on the command line:
find my-files -maxdepth 1 -type f -iname "*.txt" -exec cat {} \;
It has nothing to do with "weird" characters. \"*.txt\""
is quoted for your shell, but you're not running this in your shell. It should just be *.txt
, which is the actual argument you want find
to receive as the value for -iname
:
fullCmd := "find my-files -maxdepth 1 -type f -iname *.txt"
Though, because this is not a shell, I would strongly recommend against this approach of building a shell-like command as a single string and splitting on spaces; just provide the args as an array in the first place to avoid confusion like this.