Executing External Programs

Learn how to execute external programs using Go.


So far, we’ve developed several command-line tools with Go by executing tasks with our own algorithms. In some situations, it’s easier to delegate some of these tasks to more specialized programs that are already available on our system. For example, we might want to use Git to execute version control commands against a Git repository or launch Firefox to display a web page on a browser.

In some cases, these specialized programs have an API available that we can call directly from our program. When this isn’t available, we have to use their functionality by executing external commands from our Go program.

Go provides some lower-level libraries, such as syscall, but unless we have specific requirements, it’s best to use the higher-level interface provided by the os/exec package.

What will we learn?

In this chapter, we’ll apply the os/exec package to develop a simple, but useful, implementation of a Continuous Integration (CI) tool for our Go programs. A typical CI pipeline consists of several automated steps that continuously ensure a code base or an application is ready to be merged with some other developer’s code, usually in a shared version control repository.

For this example, the CI pipeline consists of:

  • Building the program using go build to verify that the program structure is valid.
  • Executing tests using go test to ensure the program does what it’s intended to do.
  • Executing gofmt to ensure the program’s format conforms to the standards.
  • Executing git push to push the code to the remote shared Git repository that hosts the program code.

We’ll call this tool goci. As usual, we’ll start with a primitive implementation that will grow as we move along. In this initial version of the goci tool, we’ll define the main structure of our program and then execute the first step of the CI pipeline: building the program.

Initialize a new Go module for this project called goci:

Get hands-on with 1200+ tech skills courses.