I'm trying to shell out something similar to:
diff <(echo -e "$string1" ) <(echo -e "$string2")
in Golang but all my attempts with exec.Command
have failed.
Here is the most naive attempt I have tried (CombinedOutput
is temporarily used to get the underlying issue):
func Diff(str1, str2 string) (string, error) {
cmd := exec.Command("diff", sanitize(str1), sanitize(str2))
bytes, err := cmd.CombinedOutput()
result := string(bytes)
if err != nil {
switch err.(type) {
case *exec.ExitError:
return result, nil
default:
return "", nil
}
}
return result, nil
}
Which gives me results such as: diff: \"foo
bar
baz\": No such file or directory
diff: \"foo
fighters
baz\": No such file or directory
A more involved version still does not work:
func Diff(str1, str2 string) (string, error) {
cmd := exec.Command("diff")
stdin, err := cmd.StdinPipe()
if err != nil {
return "", err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return "", err
}
err = cmd.Start()
if err != nil {
return "", err
}
io.WriteString(stdin, echoString(str1))
io.WriteString(stdin, echoString(str2))
bytes, err := ioutil.ReadAll(stdout)
cmd.Wait()
result := string(bytes)
if err != nil {
switch err.(type) {
case *exec.ExitError:
return result, nil
default:
return "", nil
}
}
return result, nil
}
func echoString(str string) string {
return fmt.Sprintf(`<( echo -e "%s" )`, strings.Replace(str, `"`, `\"`, -1))
}
There is no output at all and I get diff: missing operand after `diff'
diff: Try `diff --help' for more information.
in stderr
.
So I thought I did not really need the echo
instructions because I already got the strings, so I tried to replace echoString
implementation with just the escape part, i.e. return strings.Replace(str, `"`, `\"`, -1)
but I get the same error.
Any ideas?