如何在特定文件夹中运行Shell命令 [英] How to run a shell command in a specific folder

查看:90
本文介绍了如何在特定文件夹中运行Shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I can use this out, err := exec.Command("git", "log").Output() to get an output of the command which will run in the same path as the executable location.

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

How do I specify in which folder I want to run the command?

推荐答案

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

exec.Command() returns you a value of type *exec.Cmd. Cmd is a struct and has a Dir field:

// 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()之前进行设置即可:

So simply set it before calling Cmd.Output():

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

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

Also note that this is specific to git command; git allows you to pass the path using the -C flag, so you may also do what you want like this:

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

这篇关于如何在特定文件夹中运行Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆