douquanzhan0315 2018-10-25 21:45
浏览 96
已采纳

在Golang中使用输入重定向对diff进行外壳处理

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?

  • 写回答

1条回答 默认 最新

  • dongrong7267 2018-10-25 22:11
    关注

    Here is simplest solution, just pass diff command to bash shell:

        cmd := exec.Command(
            "bash", "-c", 
            fmt.Sprintf("diff <(echo -e %s) <(echo -e %s)", str1, str2))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度