如何在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.

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

You havent made clear why you want to change directories, this is hard to answer without context. But usually if you need a command to run from a specific directory you can specify that as the Dir property on the Command, eg:

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

If this isn't what you mean, please clarify.