doutucui0133 2017-09-03 23:37
浏览 806

如何在go中更改当前目录

Unlike Golang execute cd command for CMD, I just want to really run cd directory_location using golang 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.

  • 写回答

2条回答 默认 最新

  • dpd20130 2017-09-03 23:50
    关注

    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)
    }
    
    评论

报告相同问题?