How to Change the Current Directory in Go

Created
Modified

Using Dir Property

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:

package main

import (
  "os/exec"
)

func main() {
  cmd := exec.Command("ls", "-al")
  cmd.Dir = "/home/user"
  cmd.Run()
}

  

Using os.Chdir Function

The os.Chdir() function changes the current working directory to the named directory. If there is an error, it will be of type *PathError. For example,

package main

import (
  "fmt"
  "os"
)

func main() {

  h, _ := os.UserHomeDir()
  fmt.Println(h)

  err := os.Chdir("/root/go")
  if err != nil {
    panic(err)
  }
}
/root

This doesn't change the terminal location.

Related Tags