Menu Close

Go – How to change the current working directory in go

Here, We will see how to change the current working directory in go. We can do it by using Chdir() function in os package in go golang.

Function prototype:

func Chdir(dir string) error

Chdir() function changes the current working directory to the named directory.

Return value:

Chdir() function in os package returns 
PathError.

Example with code:

package main

import "fmt"
import "os"

func main() {

  currDir, err := os.Getwd()

  if err != nil {

    fmt.Println(err)

    return

  }

  fmt.Println(currDir)

  err = os.Chdir("/Users/joe/go-project/go-workspace/bin")

  currDir, err = os.Getwd()

  if err != nil {

    fmt.Println(err)

    return

  }

  fmt.Println(currDir)

}

Output:

/Users/joe/go-project/go-workspace/src
/Users/joe/go-project/go-workspace/bin

To learn more about golang, Please refer given below link:

https://techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *