shell 尝试使用exec.Command运行gofmt -r时出现“rune literal not terminated”错误

lxkprmvk  于 2023-01-17  发布在  Shell
关注(0)|答案(1)|浏览(234)

在下面的目录结构中,

.
├── foo.go
├── go.mod
└── main.go

我有一个带有简单类型定义的foo.go

package main

type Foo struct {
    Baz string
}

如果我从命令行运行gofmt -r来替换变量名,它会工作:

> gofmt -r 'Foo -> Bar' foo.go
package main

type Bar struct {
    Baz string
}

但是,如果我尝试使用程序从main.go执行此操作

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    combinedOutput, err := exec.Command("gofmt", "-r", "'Foo -> Bar'", "foo.go").CombinedOutput()
    if err != nil {
        log.Fatalf("gofmt foo.go: %v. Combined output: %s", err, combinedOutput)
    }
    fmt.Println(string(combinedOutput))
}

我得到一个错误:

> go run main.go
2023/01/14 23:42:07 gofmt foo.go: exit status 2. Combined output: parsing pattern 'Foo  at 1:1: rune literal not terminated
exit status 1

知道是什么引起的吗?

ef1yzkbh

ef1yzkbh1#

你不需要给exec.Command的参数加上引号;引用是shell的一个特性,在进行系统调用时不适用,也没有必要,因为引用是为了描述shell中的参数,但在exec.Command中,参数是作为函数调用的参数分开的。
具体而言:

exec.Command("gofmt", "-r", "'Foo -> Bar'", "foo.go")

应该是

exec.Command("gofmt", "-r", "Foo -> Bar", "foo.go")

相关问题