英文:
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
通常,如果你需要从特定目录运行命令,你可以将该目录指定为Command的Dir属性,例如:
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
函数就没有这个限制了
以下是一个示例用法:
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
Example usage:
home, _ := os.UserHomeDir()
err := os.Chdir(filepath.Join(home, "goproject2"))
if err != nil {
panic(err)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论