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.
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.
To navigate to your home directory, use "cd" or "cd ~" To navigate up one directory level, use "cd .." To navigate to the previous directory (or back), use "cd -" To navigate through multiple levels of directory at once, specify the full directory path that you want to go to.
To create a single directory in Go, use the os. Mkdir() function. If you want to create a hierarchy of folders (nested directories), use os. MkdirAll() .
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)
}
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With