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")