Reputation: 2118
I want to execute find
Windows command using exec
package, but windows is doing some weird escaping.
I have something like:
out, err := exec.Command("find", `"SomeText"`).Output()
but this is throwing error because Windows is converting this to
find /SomeText"
Does anyone know why? How I can execute find
on windows using exec package?
Thanks!
Upvotes: 10
Views: 4769
Reputation: 36318
OK, it's a bit more complicated than you might have expected, but there is a solution:
package main
import (
"fmt"
"os/exec"
"syscall"
)
func main() {
cmd := exec.Command(`find`)
cmd.SysProcAttr = &syscall.SysProcAttr{}
cmd.SysProcAttr.CmdLine = `find "SomeText" test.txt`
out, err := cmd.Output()
fmt.Printf("%s\n", out)
fmt.Printf("%v\n", err)
}
Unfortunately, although support for this was added in 2011, it doesn't appear to have made it into the documentation yet. (Although perhaps I just don't know where to look.)
Upvotes: 7
Reputation: 7878
FYI, running:
package main
import (
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("find", `"SomeText"`)
fmt.Printf("Path: %q, args[1]: %q\n", cmd.Path, cmd.Args[1])
}
On unix gives:
Path: "/usr/bin/find", args[1]: "\"SomeText\""
And cross compiled to Windows and run on Win7 gives:
Path: "C:\\Windows\\system32\\find.exe", args[1]: "\"SomeText\""
Both look correct to me.
Adding out, err := cmd.Output()
to the Windows cross-compile gives the following for fmt.Printf("%#v\%v\n", err, err)
:
&exec.ExitError{ProcessState:(*os.ProcessState)(0xc0820046a0)}
exit status 1
But I imagine that's just because find fails to find anything.
Upvotes: 0