Using exec in GoLang

Exec is a subpackage in os package. It can be used to run external commands using Go. This post will provide some examples of how to get started using it.

Required imports

To use this package we need to import as follows:

import "os/exec"

Running commands using GoLang exec Package

We can run any commands we wish. Just like we use CMD, bash or some other shell to run command, it can run those commands.

Here is an example of running the DIR command.

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	cmd := exec.Command("dir")

	e := cmd.Run()
	CheckError(e)
}

func CheckError(e error) {
	if e != nil {
		fmt.Println(e)
	}
}

Now, the program will run but we won’t see any output to the console. The reason is that the command is run and the output is not sent to the standard output.

So, we need to fix it. Two lines shown below are to be added to see any output to the console.

cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr

The output will show files inside the current directory.

Specifying commands for different OS

We can specify the commands to run differently for different OS (e.g. bash command on Linux). Here is an example.

if runtime.GOOS == "linux" {
	cmd = exec.Command("ls")
}

For this to run, we need to import the runtime package as well.

To see all possible OS we can run go tool dist list and it will show all possible OS and ARCH combinations.