开发者社区> 问答> 正文

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

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

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

展开
收起
游客ufivfoddcd53c 2020-01-04 11:51:06 1308 0
1 条回答
写回答
取消 提交回答
  • exec.Command()返回一个type值*exec.Cmd。Cmd是一个struct并具有一个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
    
    

    因此,只需在调用之前进行设置Cmd.Output():

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

    另请注意,这特定于git命令;git允许您使用-C标志传递路径,因此您也可以像这样进行操作:

    out, err := exec.Command("git", "-C", "your/intended/working/directory", "log").
        Output()
    
    2020-01-04 11:51:35
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
RocketMQ Client-GO 介绍 立即下载
Go语言路上踩过的坑 立即下载
gohbase :HBase go客户端 立即下载

相关镜像