简体   繁体   English

如何在 Go 中更改当前目录

[英]How to change the current directory in Go

Unlike Execute the 'cd' command for CMD in Go , I just want to really run cd directory_location using Go and change the current directory.在 Go 中为 CMD 执行 'cd' 命令不同,我只想真正使用 Go 运行cd directory_location并更改当前目录。

So for example,例如,

Say I am on ~/goproject, and I run, ./main in the terminal, I want to be at ~/goproject2 in the terminal.假设我在 ~/goproject 上,我在终端中运行./main ,我想在终端中的 ~/goproject2 。

I tried我试过了

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

But this didn't actually change the current directory.但这实际上并没有改变当前目录。

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:通常,如果您需要从特定目录运行命令,您可以将其指定为CommandDir属性,例如:

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

You want os.Chdir .你想要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.如果您需要更改shell 工作目录,最好的办法是查看cd工作方式并从中恢复。

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 :)正如您所发现的,您不能使用cd从应用程序内部更改当前目录,但是使用os.Chdir则不需要它工作:)

Example usage:用法示例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM