Golang os.Chdir() function is “used to change the current working directory to the named directory.” If there is an error, it will be of type *PathError.
Syntax
func Chdir(dir string) error
Parameters
dir(string): The name of the directory to which you want to change the current working directory.
Return value
If successful, Chdir() returns nil. If there’s an error, it returns a non-nil error.
Example 1: How to Use os.Chdir() function
package main
import (
"fmt"
"os"
)
func main() {
// Getting the current working directory
initialDir, _ := os.Getwd()
fmt.Println("Initial Directory:", initialDir)
// Changing the current working directory to /tmp
err := os.Chdir("/tmp")
if err != nil {
fmt.Println("Error:", err)
return
}
// Getting the new current working directory
newDir, _ := os.Getwd()
fmt.Println("New Directory:", newDir)
}
Output
When you run the above code, it will print the initial working directory, change it to /tmp
(or another directory if you modify the code), and then print the new working directory.
Example 2: Change the Directory and List the Files
package main
import (
"fmt"
"io/ioutil"
"os"
)
func main() {
targetDir := "/tmp"
// Change the current working directory to the target directory
err := os.Chdir(targetDir)
if err != nil {
fmt.Println("Error changing directory:", err)
return
}
// List all files in the new directory
files, err := ioutil.ReadDir(targetDir)
if err != nil {
fmt.Println("Error reading directory:", err)
return
}
fmt.Println("Files in", targetDir, ":")
for _, file := range files {
fmt.Println(" -", file.Name())
}
}
Output
Example 3: Nested Directory Change
package main
import (
"fmt"
"os"
)
func main() {
targetDir := "/tmp"
// Change the current working directory to the target directory
err := os.Chdir(targetDir)
if err != nil {
fmt.Println("Error changing directory:", err)
return
}
// Navigate one directory deeper (assuming a directory named 'example' exists)
err = os.Chdir("example")
if err != nil {
fmt.Println("Error changing to nested directory:", err)
return
}
// Print the current directory
currentDir, _ := os.Getwd()
fmt.Println("Current Directory:", currentDir)
}
Output
Error changing to nested directory: chdir example: no such file or directory
That’s it!
Related posts

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.