Cd not seen by exec.Command()

Hello. I found something strange (well, for me, hopefully there is no magic behind).

This works fine and dandy:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	out, err := exec.Command("ls", "-la").Output()
	if err != nil {
		fmt.Printf("%s", err)
	} else {
		fmt.Println(string(out[:]))
	}
}

But the below does not:

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	out, err = exec.Command("cd", "../mydir").Output()
	if err != nil {
		fmt.Printf("%s", err)
	} else {
		fmt.Println(string(out[:]))
	}

}

I am getting the following error:

exec: "cd": executable file not found in $PATH

Why exec.Command() does not recognize cd?

INFO:

  • WSL 1 (Ubuntu 20.4) under Windows 10
  • go version go1.16.3 linux/amd64
1 Like

cd is not a program. It’s a statement in your shell. You could do something like exec.Command("bash", "-c", "cd ../mydir"), but that would be useless because cd changes the working directory of the current process (i.e. bash, in this case), so your own program would still be in its own current working directory.

If you want to change the directory that your program is working from, use os.Chdir.

2 Likes

Oh man. Thanks, I appreciate this. I thought (and hoped) it was something like this, but I was amazed because I used cd in the corresponding system commands in several other languages and it always worked.

Thank you!