Search code examples
windowsgocdchdir

Cannot change directory using os.Chdir()


os.Chdir() in golang is not working properly.

package main

import (
    "fmt"
    "os"
)

func main() {
    command := "cd C:\\"
    if err := os.Chdir(command[3:]); err != nil {
        fmt.Println("Error:\tCould not move into the directory (%s)\n")
    }
}

Outputs:

Error:   Could not move into the directory

Am I doing something wrong or missing something?


Solution

  • You don't have minimal, reproducible example. See: How to create a Minimal, Reproducible Example.

    Here is a minimum, reproducible example for your code, discarding all but essential code and printing input, output, and errors.

    package main
    
    import (
        "fmt"
        "os"
        "runtime"
    )
    
    func main() {
        fmt.Println(os.Getwd())
        dir := `C:\`
        if runtime.GOOS != "windows" {
            dir = `/`
        }
        err := os.Chdir(dir)
        fmt.Println(dir, err)
        fmt.Println(os.Getwd())
    }
    

    Output:

    Windows:

    C:\Users\peter>go run chdir.go
    C:\Users\peter <nil>
    C:\ <nil>
    C:\ <nil>
    C:\Users\peter>
    

    Linux:

    $ go run chdir.go
    /home/peter <nil>
    / <nil>
    / <nil>
    $ 
    

    It works.

    Run it and compare it to your code.