Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change the current directory in Go

Tags:

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.

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.

like image 538
Jason Kim Avatar asked Sep 03 '17 23:09

Jason Kim


People also ask

What is the command to go to 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.

How do I create a folder in Go?

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() .


2 Answers

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)
}
like image 109
Milo Christiansen Avatar answered Oct 18 '22 02:10

Milo Christiansen


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()
like image 21
SwiftD Avatar answered Oct 18 '22 03:10

SwiftD