How to change the current directory in Go

huangapple go评论80阅读模式
英文:

How to change the current directory in Go

问题

不同于https://stackoverflow.com/questions/44206940/golang-execute-cd-command-for-cmd,我只想真正地在Go中运行cd directory_location命令并更改当前目录。

例如,

假设我在~/goproject目录下,在终端中运行./main命令后,我希望在终端中切换到~/goproject2目录。

我尝试了以下代码:

cmd := exec.Command("bash", "-c", "cd", "~/goproject2")
cmd.Run()

但是这并没有实际改变当前目录。

英文:

Unlike https://stackoverflow.com/questions/44206940/golang-execute-cd-command-for-cmd, I just want to really run cd directory_location using Go and change the current directory.

So for example,

Say I am on ~/goproject, and I run, ./main in the terminal, I want to be at ~/goproject2 in the terminal.

I tried

cmd := exec.Command("bash", "-c", "cd", "~/goproject2")
cmd.Run()

But this didn't actually change the current directory.

答案1

得分: 41

通常,如果你需要从特定目录运行命令,你可以将该目录指定为CommandDir属性,例如:

cmd := exec.Command("myCommand", "arg1", "arg2")
cmd.Dir = "/path/to/work/dir"
cmd.Run()

这样,命令将在指定的目录下运行。

英文:

Usually if you need a command to run from a specific directory, you can specify that as the Dir property on the Command, for example:

cmd := exec.Command("myCommand", "arg1", "arg2")
cmd.Dir = "/path/to/work/dir"
cmd.Run()

答案2

得分: 31

你想要使用os.Chdir函数。这个函数可以改变应用程序的工作目录。如果你需要改变shell的工作目录,最好的方法是查找cd命令的工作原理,并从那里开始思考。

正如你已经发现的那样,你不能在应用程序内部使用cd命令来改变当前目录,但是使用os.Chdir函数就没有这个限制了 How to change the current directory in Go

以下是一个示例用法:

home, _ := os.UserHomeDir()
err := os.Chdir(filepath.Join(home, "goproject2"))
if err != nil {
    panic(err)
}
英文:

You want os.Chdir. This function will change the application working directory. If you need to change the shell working directory, your best bet is to look up how cd works and work back from that.

As you have discovered, you cannot use cd to change your current directory from inside an application, but with os.Chdir there is no need for it to work How to change the current directory in Go

Example usage:

home, _ := os.UserHomeDir()
err := os.Chdir(filepath.Join(home, "goproject2"))
if err != nil {
    panic(err)
}

huangapple
  • 本文由 发表于 2017年9月4日 07:37:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/46028707.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定