2

I'm creating a CLI tool in Golang, and I'm new to both Golang and making tools for the terminal. I need to execute terminal commands right from my program (specifically cd). How do I do this? I followed along with this post, but it threw an error saying that echo wasn't found in %path%

Thanks in advance for any help!

4 Answers4

4

os/exec package helps you execute terminal commands in Go.

Executing system commands is quite simple. Cmd holds your external command.

So in linux suppose you want to run "echo hello" command, you'd write the following code.

cmdStruct := exec.Command("echo","hello")    
out,err := cmdStruct.Output()
if err != nil {
    fmt.Println(err)
}
fmt.Println(string(out))

This is one of the most basic way. However, in Windows, you need to pass "echo hello" as an argument to Command prompt or Powershell.

    cmdStruct:= exec.Command("cmd.exe","/c","echo","hello")

To simplify this pass arguments in a single slice,

args:= strings.Split("/c echo hello there how are you"," ")
cmdStruct:= exec.Command("cmd.exe",args...)

Check out this answer for a better understanding and an enhanced version of this code.

For cd you can use os.Chdir() and os.Getwd() to change and view your working directory respectively. But if you require your command to execute in a specific directory tou can set Dir of your command i.e.

cmdStruct.Dir = "path/to/directory"

or

cmdStruct.Dir = filepath.Join("path","to","directory")
retrologic
  • 117
  • 6
2

Implement the cd command by calling os.Chdir.

Because a subprocess cannot change the working directory of a parent process, there is not a separate executable for the cd command. The cd command is builtin to command line interpreters.

1

cd is not a external program.

The command line interpreter has an abstraction “current dir”, that affects all other commands. It is a state

It is used to handle relative paths, for instance.

If you want to create your CLI from scratch you must define how this stage affects everything.

If you need to interact to an existing CLI, you need to start it in a OS process and interact via streams.

There are 3 streams:

STDIN - input STDOUT - output STDERR - for error

You need to capture the user commands and send to the STDIN of the CLI. And read both STDIN / STDOUT to write a response.

This is something to do with goroutines, for instance

Tiago Peczenyj
  • 4,387
  • 2
  • 22
  • 35
1

Even though it's been quite a while since I asked this, I figured it would be good to answer this. To put it simply, there's no way. Programs essentially run on their own little contained box, which means while os.Chdir() does technically change the working directory, it "reverts back" afterwards.