如何使用Golang在特定文件夹中运行shell命令?

Ser*_*rov 19 go

我可以使用它out, err := exec.Command("git", "log").Output()来获取命令的输出,该输出将在与可执行位置相同的路径中运行.

如何指定要在哪个文件夹中运行命令?

icz*_*cza 53

exec.Command()返回值类型*exec.Cmd.Cmd是一个结构,并有一个Dir字段:

// Dir specifies the working directory of the command.
// If Dir is the empty string, Run runs the command in the
// calling process's current directory.
Dir string
Run Code Online (Sandbox Code Playgroud)

所以只需在调用之前设置它Cmd.Output():

cmd:= exec.Command("git", "log")
cmd.Dir = "your/intended/working/directory"
out, err := cmd.Output()
Run Code Online (Sandbox Code Playgroud)

另请注意,这是针对git命令的; git允许你使用-C标志传递路径,所以你也可以这样做:

out, err := exec.Command("git", "-C", "your/intended/working/directory", "log").
    Output()
Run Code Online (Sandbox Code Playgroud)