问题
I am trying to patch a file using the below command
patch -p0 < <file_path>
My runCommand syntax is as below:
func runCommand(cmd string, args ...string) error {
ecmd := exec.Command(cmd, args...)
ecmd.Stdout = os.Stdout
ecmd.Stderr = os.Stderr
ecmd.Stdin = os.Stdin
err := ecmd.Run()
return err
}
Now I am passing my patch command as below:
cmd = "patch"
args := []string{"-p0", "<", "/tmp/file"}
err = runCommand(cmd, args...)
But I am seeing the below error:
patch: **** Can't find file '<' : No such file or directory
Can you please let me know what I am missing here?
回答1:
You're missing this paragraph from the documentation:
Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells. The package behaves more like C's "exec" family of functions. To expand glob patterns, either call the shell directly, taking care to escape any dangerous input, or use the path/filepath package's Glob function. To expand environment variables, use package os's ExpandEnv.
The shell is responsible for handling <
operations. You can set stdin
yourself with the file as input or you can use the shell. To use the shell, try something like:
runCommand("/bin/sh", "patch -p0 < /tmp/file")
Note that this won't work on Windows. Reading the file and writing to stdin
yourself is a more easily portable solution.
来源:https://stackoverflow.com/questions/47610873/exec-command-for-patch-command