Home > OS >  How do you execute terminal commands from Golang?
How do you execute terminal commands from Golang?

Time:04-03

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!

CodePudding user response:

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

CodePudding user response:

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.

  • Related